feat: retain encrypted instance credentials and reissue v2 certificates
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-12 11:41:02 +08:00
parent fad1fba710
commit 9ba8053b5b
21 changed files with 449 additions and 39 deletions

View File

@@ -35,3 +35,6 @@ PACKAGE_STORAGE_ROOT=
# Compose external path variables (not secret values): MYSQL_APP_SECRET_FILE, # Compose external path variables (not secret values): MYSQL_APP_SECRET_FILE,
# MYSQL_ROOT_SECRET_FILE, LICENSE_SIGNING_KEY_HOST_FILE, PACKAGE_STORAGE_HOST. # MYSQL_ROOT_SECRET_FILE, LICENSE_SIGNING_KEY_HOST_FILE, PACKAGE_STORAGE_HOST.
# See docs/deployment-delivery.md for outstanding TLS/cookie/restore blockers. # See docs/deployment-delivery.md for outstanding TLS/cookie/restore blockers.
# Optional independent 32-byte raw AES-GCM key; absolute path, secure backup.
LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE=

View File

@@ -48,7 +48,7 @@ func run() error {
if err != nil { if err != nil {
return err return err
} }
httpapi.RegisterBusinessWithKeyring(router, db, cfg.SigningPrivateKeyPEM, ring) httpapi.RegisterBusinessWithKeyring(router, db, cfg.SigningPrivateKeyPEM, ring, cfg.CredentialEncryptionKey)
} }
// Readiness is registered only on the loopback operations listener. // Readiness is registered only on the loopback operations listener.
if err := router.SetTrustedProxies(cfg.TrustedProxies); err != nil { if err := router.SetTrustedProxies(cfg.TrustedProxies); err != nil {

View File

@@ -11,14 +11,15 @@ import (
) )
type Config struct { type Config struct {
HTTPAddr string HTTPAddr string
TrustedProxies []string TrustedProxies []string
ReadHeaderTimeout time.Duration ReadHeaderTimeout time.Duration
ReadTimeout time.Duration ReadTimeout time.Duration
WriteTimeout time.Duration WriteTimeout time.Duration
IdleTimeout time.Duration IdleTimeout time.Duration
ShutdownTimeout time.Duration ShutdownTimeout time.Duration
SigningPrivateKeyPEM string SigningPrivateKeyPEM string
CredentialEncryptionKey []byte
} }
func Load(getenv func(string) string) (Config, error) { func Load(getenv func(string) string) (Config, error) {
@@ -85,6 +86,16 @@ func Load(getenv func(string) string) (Config, error) {
} }
c.SigningPrivateKeyPEM = string(data) c.SigningPrivateKeyPEM = string(data)
} }
if path := getenv("LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE"); path != "" {
if !filepath.IsAbs(path) {
return Config{}, fmt.Errorf("credential encryption key path must be absolute")
}
data, err := os.ReadFile(path)
if err != nil || len(data) != 32 {
return Config{}, fmt.Errorf("credential encryption key must be exactly 32 raw bytes")
}
c.CredentialEncryptionKey = data
}
if root := getenv("PACKAGE_STORAGE_ROOT"); root != "" { if root := getenv("PACKAGE_STORAGE_ROOT"); root != "" {
if !filepath.IsAbs(root) { if !filepath.IsAbs(root) {
return Config{}, fmt.Errorf("PACKAGE_STORAGE_ROOT must be absolute") return Config{}, fmt.Errorf("PACKAGE_STORAGE_ROOT must be absolute")

View File

@@ -62,3 +62,25 @@ func TestLoadRejectsInvalid(t *testing.T) {
}) })
} }
} }
func TestCredentialKeyFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "credentials.key")
for _, size := range []int{31, 32, 33} {
if err := os.WriteFile(path, make([]byte, size), 0600); err != nil {
t.Fatal(err)
}
c, err := Load(func(name string) string {
if name == "LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE" {
return path
}
return ""
})
if size == 32 {
if err != nil || len(c.CredentialEncryptionKey) != 32 {
t.Fatal("valid key rejected")
}
} else if err == nil {
t.Fatal("invalid length accepted")
}
}
}

View File

@@ -20,7 +20,21 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func instanceOnlineState(last *time.Time, now time.Time) string {
if last == nil {
return "never_seen"
}
if last.After(now) {
return "unknown"
}
if now.Sub(*last) <= 3*time.Minute {
return "online"
}
return "offline"
}
type instanceRecord struct { type instanceRecord struct {
OnlineState string `json:"online_state"`
ID uint64 `json:"id"` ID uint64 `json:"id"`
InstanceID string `json:"instance_id"` InstanceID string `json:"instance_id"`
LicenseID uint64 `json:"license_id"` LicenseID uint64 `json:"license_id"`
@@ -98,6 +112,14 @@ func (a *BusinessAPI) provisionInstance(c *gin.Context) {
} }
secret := base64.RawURLEncoding.EncodeToString(secretBytes) secret := base64.RawURLEncoding.EncodeToString(secretBytes)
hash := sha256.Sum256(secretBytes) hash := sha256.Sum256(secretBytes)
var encrypted []byte
if len(a.credentialEncryptionKey) > 0 {
encrypted, err = sealInstanceSecret(a.credentialEncryptionKey, instanceID, secret)
if err != nil {
apiError(c, 503, "credentials_unavailable", "凭据加密不可用")
return
}
}
tx, err := a.db.BeginTx(c, nil) tx, err := a.db.BeginTx(c, nil)
if err != nil { if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用") apiError(c, 500, "internal_error", "服务暂时不可用")
@@ -126,7 +148,7 @@ func (a *BusinessAPI) provisionInstance(c *gin.Context) {
return return
} }
var id uint64 var id uint64
res, err := tx.ExecContext(c, "INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by) VALUES(?,?,?,?,?,?)", instanceID, licenseID, customerID, productID, hash[:], actor) res, err := tx.ExecContext(c, "INSERT INTO license_instances(instance_id,license_id,customer_id,product_id,secret_hash,created_by,secret_encrypted) VALUES(?,?,?,?,?,?,?)", instanceID, licenseID, customerID, productID, hash[:], actor, encrypted)
if err != nil { if err != nil {
apiError(c, 409, "instance_conflict", "实例创建失败") apiError(c, 409, "instance_conflict", "实例创建失败")
return return
@@ -143,7 +165,7 @@ func (a *BusinessAPI) provisionInstance(c *gin.Context) {
return return
} }
c.Header("Cache-Control", "no-store") c.Header("Cache-Control", "no-store")
c.JSON(201, gin.H{"data": gin.H{"id": id, "instance_id": instanceID, "license_id": licenseID, "status": "provisioned", "secret": secret}, "secret_expires": "one-time"}) c.JSON(201, gin.H{"data": gin.H{"id": id, "instance_id": instanceID, "license_id": licenseID, "status": "provisioned", "secret": secret}, "credentials_retained": len(encrypted) > 0})
} }
func (a *BusinessAPI) listInstances(c *gin.Context) { func (a *BusinessAPI) listInstances(c *gin.Context) {
@@ -165,12 +187,14 @@ func (a *BusinessAPI) listInstances(c *gin.Context) {
apiError(c, 500, "internal_error", "服务暂时不可用") apiError(c, 500, "internal_error", "服务暂时不可用")
return return
} }
x.OnlineState = instanceOnlineState(x.LastSeenAt, time.Now().UTC())
out = append(out, x) out = append(out, x)
} }
c.JSON(200, gin.H{"data": out}) c.JSON(200, gin.H{"data": out})
} }
func (a *BusinessAPI) activateInstance(c *gin.Context) { func (a *BusinessAPI) activateInstance(c *gin.Context) {
c.Header("Cache-Control", "no-store")
if a.signingPrivateKeyPEM == "" { if a.signingPrivateKeyPEM == "" {
apiError(c, 503, "signing_unavailable", "签名密钥未配置") apiError(c, 503, "signing_unavailable", "签名密钥未配置")
return return
@@ -254,10 +278,24 @@ func (a *BusinessAPI) activateInstance(c *gin.Context) {
apiError(c, 403, "forbidden", "实例secret无效") apiError(c, 403, "forbidden", "实例secret无效")
return return
} }
if inst.Status == "activated" { reissuing := inst.Status == "activated" && a.keyring != nil
if inst.Status == "activated" && !reissuing {
apiError(c, 409, "invalid_state", "实例已经激活") apiError(c, 409, "invalid_state", "实例已经激活")
return return
} }
if inst.Status != "provisioned" && !reissuing {
apiError(c, 409, "invalid_state", "实例状态不允许签发")
return
}
var freeze string
if err = tx.QueryRowContext(c, "SELECT freeze_state FROM license_instances WHERE id=?", inst.ID).Scan(&freeze); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if freeze != "none" {
apiError(c, 409, "invalid_state", "实例已冻结")
return
}
var licenseStatus, customerStatus string var licenseStatus, customerStatus string
var productActive bool var productActive bool
var licenseCustomer, licenseProduct uint64 var licenseCustomer, licenseProduct uint64
@@ -315,7 +353,7 @@ func (a *BusinessAPI) activateInstance(c *gin.Context) {
} }
payloadJSON, _ := json.Marshal(payload) payloadJSON, _ := json.Marshal(payload)
now := time.Now().UTC().Truncate(time.Microsecond) now := time.Now().UTC().Truncate(time.Microsecond)
if _, err = tx.ExecContext(c, "UPDATE license_instances SET status='activated',activated_at=?,certificate_version=?,certificate_payload=?,certificate_signature=? WHERE id=?", now, version, payloadJSON, base64.RawStdEncoding.EncodeToString(signature), inst.ID); err != nil { if _, err = tx.ExecContext(c, "UPDATE license_instances SET status='activated',activated_at=COALESCE(activated_at,?),certificate_version=?,certificate_payload=?,certificate_signature=? WHERE id=?", now, version, payloadJSON, base64.RawStdEncoding.EncodeToString(signature), inst.ID); err != nil {
apiError(c, 500, "internal_error", "激活失败") apiError(c, 500, "internal_error", "激活失败")
return return
} }
@@ -326,7 +364,11 @@ func (a *BusinessAPI) activateInstance(c *gin.Context) {
return return
} }
details, _ := json.Marshal(gin.H{"instance_id": instanceID, "license_id": inst.LicenseID, "certificate_version": version}) details, _ := json.Marshal(gin.H{"instance_id": instanceID, "license_id": inst.LicenseID, "certificate_version": version})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.activated','license_instance',?,?)", actor, inst.ID, details); err != nil { action := "instance.activated"
if reissuing {
action = "instance.certificate.reissued"
}
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?,'license_instance',?,?)", actor, action, inst.ID, details); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用") apiError(c, 500, "internal_error", "服务暂时不可用")
return return
} }
@@ -334,6 +376,10 @@ func (a *BusinessAPI) activateInstance(c *gin.Context) {
apiError(c, 500, "internal_error", "服务暂时不可用") apiError(c, 500, "internal_error", "服务暂时不可用")
return return
} }
if reissuing {
c.JSON(200, response)
return
}
c.JSON(201, response) c.JSON(201, response)
} }

View File

@@ -4,8 +4,10 @@ import (
"crypto/ecdsa" "crypto/ecdsa"
"crypto/elliptic" "crypto/elliptic"
"crypto/rand" "crypto/rand"
"crypto/sha256"
"crypto/x509" "crypto/x509"
"database/sql" "database/sql"
"encoding/base64"
"encoding/json" "encoding/json"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
@@ -15,6 +17,7 @@ import (
"strings" "strings"
"sync" "sync"
"testing" "testing"
"time"
) )
func testActivationMySQL(t *testing.T, db *sql.DB, cookie *http.Cookie) { func testActivationMySQL(t *testing.T, db *sql.DB, cookie *http.Cookie) {
@@ -123,6 +126,96 @@ func testActivationMySQL(t *testing.T, db *sql.DB, cookie *http.Cookie) {
if err = db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='instance.activated'").Scan(&count); err != nil || count != 1 { if err = db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='instance.activated'").Scan(&count); err != nil || count != 1 {
t.Fatal("activation audit count mismatch") t.Fatal("activation audit count mismatch")
} }
t.Run("v2-reissue", func(t *testing.T) {
publicDER, _ := x509.MarshalPKIXPublicKey(&key.PublicKey)
ring := &Keyring{Current: "production-test", Keys: []VerificationKey{{KeyID: "production-test", PublicKeyPEM: string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER}))}}}
r2 := NewRouter()
RegisterBusinessWithKeyring(r2, db, string(pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der})), ring)
req := func(b, idem string) *httptest.ResponseRecorder {
q := httptest.NewRequest("POST", path, strings.NewReader(b))
q.Header.Set("Content-Type", "application/json")
q.Header.Set("Idempotency-Key", idem)
w := httptest.NewRecorder()
r2.ServeHTTP(w, q)
return w
}
var activated time.Time
db.QueryRow("SELECT activated_at FROM license_instances WHERE instance_id=?", instanceID).Scan(&activated)
if w := req(string(badBytes), "v2-invalid"); w.Code != 403 {
t.Fatalf("bad credential=%d", w.Code)
}
db.Exec("UPDATE license_instances SET freeze_state='frozen' WHERE instance_id=?", instanceID)
if w := req(body, "v2-frozen"); w.Code != 409 {
t.Fatalf("frozen=%d", w.Code)
}
db.Exec("UPDATE license_instances SET freeze_state='none' WHERE instance_id=?", instanceID)
db.Exec("UPDATE licenses SET status='revoked' WHERE id=?", licenseID)
if w := req(body, "v2-revoked"); w.Code != 409 {
t.Fatalf("revoked=%d", w.Code)
}
db.Exec("UPDATE licenses SET status='active' WHERE id=?", licenseID)
var wg sync.WaitGroup
results := make(chan *httptest.ResponseRecorder, 2)
for i := 0; i < 2; i++ {
wg.Add(1)
go func() { defer wg.Done(); results <- req(body, "v2-upgrade") }()
}
wg.Wait()
close(results)
var envelope []byte
for w := range results {
if w.Code != 200 {
t.Fatalf("reissue=%d %s", w.Code, w.Body.String())
}
if envelope != nil && string(envelope) != w.Body.String() {
t.Fatal("idempotent responses differ")
}
envelope = w.Body.Bytes()
}
var response struct {
Data struct {
Certificate struct {
Payload struct {
Version string `json:"version"`
KeyID string `json:"key_id"`
Instance string `json:"instance_id"`
Starts time.Time `json:"starts_at"`
Expires time.Time `json:"expires_at"`
}
Signature string
}
}
}
if err := json.Unmarshal(envelope, &response); err != nil {
t.Fatal(err)
}
cert := response.Data.Certificate
if cert.Payload.Version != "license-v2" || cert.Payload.KeyID != ring.Current || cert.Payload.Instance != instanceID {
t.Fatal("v2 binding missing")
}
var customer, product uint64
db.QueryRow("SELECT customer_id,product_id FROM licenses WHERE id=?", licenseID).Scan(&customer, &product)
canonical := canonicalCertificatePayload("license-v2", instanceID, licenseID, customer, product, cert.Payload.Starts, cert.Payload.Expires) + "\nkey_id=" + ring.Current
digest := sha256.Sum256([]byte(canonical))
signature, _ := base64.RawStdEncoding.DecodeString(cert.Signature)
if !ecdsa.VerifyASN1(&key.PublicKey, digest[:], signature) {
t.Fatal("v2 signature invalid")
}
var after time.Time
db.QueryRow("SELECT activated_at FROM license_instances WHERE instance_id=?", instanceID).Scan(&after)
if !activated.Equal(after) {
t.Fatal("activation timestamp changed")
}
var count int
db.QueryRow("SELECT COUNT(*) FROM audit_events WHERE action='instance.certificate.reissued'").Scan(&count)
if count != 1 {
t.Fatal("reissue audit not atomic")
}
if w := req(body, "activate"); w.Code != 200 || !strings.Contains(w.Body.String(), "license-v1") {
t.Fatal("legacy replay changed")
}
})
t.Run("heartbeat", func(t *testing.T) { t.Run("heartbeat", func(t *testing.T) {
testHeartbeatMySQL(t, db, r, cookie, instanceID, secret, licenseID, &key.PublicKey) testHeartbeatMySQL(t, db, r, cookie, instanceID, secret, licenseID, &key.PublicKey)
}) })

View File

@@ -16,9 +16,10 @@ import (
) )
type BusinessAPI struct { type BusinessAPI struct {
db *sql.DB db *sql.DB
signingPrivateKeyPEM string signingPrivateKeyPEM string
keyring *Keyring keyring *Keyring
credentialEncryptionKey []byte
} }
func secureSessionCookie(c *gin.Context) bool { func secureSessionCookie(c *gin.Context) bool {
@@ -35,11 +36,15 @@ func RegisterBusiness(r *gin.Engine, db *sql.DB, signingPrivateKeyPEM ...string)
} }
registerBusinessRoutes(r, a) registerBusinessRoutes(r, a)
} }
func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring *Keyring) { func RegisterBusinessWithKeyring(r *gin.Engine, db *sql.DB, private string, ring *Keyring, credentialKey ...[]byte) {
if db == nil { if db == nil {
return return
} }
registerBusinessRoutes(r, &BusinessAPI{db: db, signingPrivateKeyPEM: private, keyring: ring}) a := &BusinessAPI{db: db, signingPrivateKeyPEM: private, keyring: ring}
if len(credentialKey) > 0 {
a.credentialEncryptionKey = credentialKey[0]
}
registerBusinessRoutes(r, a)
} }
func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) { func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
api := r.Group("/api/v1") api := r.Group("/api/v1")
@@ -87,6 +92,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
secured.GET("/licenses/:id", a.getLicense) secured.GET("/licenses/:id", a.getLicense)
secured.GET("/licenses/:id/instances", a.listInstances) secured.GET("/licenses/:id/instances", a.listInstances)
secured.POST("/licenses/:id/instances", a.provisionInstance) secured.POST("/licenses/:id/instances", a.provisionInstance)
secured.GET("/licenses/:id/instance-credentials", a.instanceCredentials)
secured.POST("/products/:id/releases", a.createRelease) secured.POST("/products/:id/releases", a.createRelease)
secured.GET("/products/:id/releases", a.listReleases) secured.GET("/products/:id/releases", a.listReleases)
api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease) api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease)

View File

@@ -0,0 +1,82 @@
package httpapi
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"database/sql"
"errors"
"strconv"
"github.com/gin-gonic/gin"
)
func sealInstanceSecret(key []byte, instanceID, secret string) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, []byte(secret), []byte("instance-secret-v1:"+instanceID)), nil
}
func openInstanceSecret(key []byte, instanceID string, data []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
if len(data) < gcm.NonceSize() {
return "", errors.New("invalid ciphertext")
}
plain, err := gcm.Open(nil, data[:gcm.NonceSize()], data[gcm.NonceSize():], []byte("instance-secret-v1:"+instanceID))
return string(plain), err
}
func (a *BusinessAPI) instanceCredentials(c *gin.Context) {
c.Header("Cache-Control", "no-store")
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
apiError(c, 400, "invalid_request", "授权 ID 无效")
return
}
var instanceID, licenseKey string
var encrypted []byte
err = a.db.QueryRowContext(c, `SELECT i.instance_id,l.license_key,i.secret_encrypted FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.license_id=?`, id).Scan(&instanceID, &licenseKey, &encrypted)
if errors.Is(err, sql.ErrNoRows) {
apiError(c, 404, "not_found", "实例不存在")
return
}
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if len(encrypted) == 0 {
apiError(c, 409, "credentials_not_retained", "旧实例仅保存密钥哈希,无法恢复激活凭据;请使用原始交付文件或重新签发授权")
return
}
if len(a.credentialEncryptionKey) == 0 {
apiError(c, 503, "credentials_unavailable", "未配置凭据加密密钥")
return
}
secret, err := openInstanceSecret(a.credentialEncryptionKey, instanceID, encrypted)
if err != nil {
apiError(c, 503, "credentials_unavailable", "凭据解密不可用,请检查加密密钥配置")
return
}
// No credential material in audit details. Do not disclose before audit succeeds.
_, err = a.db.ExecContext(c, `INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.credentials.viewed','license',?,?)`, c.MustGet("admin_id"), id, `{}`)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.JSON(200, gin.H{"data": gin.H{"instance_id": instanceID, "license_key": licenseKey, "secret": secret}})
}

View File

@@ -0,0 +1,118 @@
package httpapi
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"errors"
"github.com/gin-gonic/gin"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestInstanceSecretEncryption(t *testing.T) {
key := bytes.Repeat([]byte{7}, 32)
data, err := sealInstanceSecret(key, "instance-a", "test-secret")
if err != nil || bytes.Contains(data, []byte("test-secret")) {
t.Fatal("encryption failed")
}
plain, err := openInstanceSecret(key, "instance-a", data)
if err != nil || plain != "test-secret" {
t.Fatal("roundtrip failed")
}
if _, err = openInstanceSecret(key, "instance-b", data); err == nil {
t.Fatal("cross-instance replay accepted")
}
if _, err = openInstanceSecret(bytes.Repeat([]byte{8}, 32), "instance-a", data); err == nil {
t.Fatal("wrong key accepted")
}
data[len(data)-1] ^= 1
if _, err = openInstanceSecret(key, "instance-a", data); err == nil {
t.Fatal("tampering accepted")
}
if _, err = openInstanceSecret(key, "instance-a", nil); err == nil {
t.Fatal("empty accepted")
}
}
func TestInstanceCredentialsLegacy(t *testing.T) {
db, _ := newDashboardTestDB(t, []dashboardQuery{{sql: `SELECT i.instance_id,l.license_key,i.secret_encrypted FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.license_id=?`, args: []any{int64(2)}, rows: [][]driver.Value{{"instance-a", "test-license", nil}}}})
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/", nil)
c.Params = gin.Params{{Key: "id", Value: "2"}}
(&BusinessAPI{db: db}).instanceCredentials(c)
if w.Code != 409 || !strings.Contains(w.Body.String(), "credentials_not_retained") || w.Header().Get("Cache-Control") != "no-store" || strings.Contains(w.Body.String(), "test-license") {
t.Fatal("legacy credential disclosure")
}
}
func TestInstanceOnlineState(t *testing.T) {
now := time.Now().UTC()
for _, tc := range []struct {
age time.Duration
want string
}{{0, "online"}, {3 * time.Minute, "online"}, {3*time.Minute + time.Nanosecond, "offline"}, {-time.Second, "unknown"}} {
last := now.Add(-tc.age)
if instanceOnlineState(&last, now) != tc.want {
t.Fatal(tc.want)
}
}
if instanceOnlineState(nil, now) != "never_seen" {
t.Fatal("never seen")
}
}
func TestInstanceCredentialsRequiresSession(t *testing.T) {
db, _ := newDashboardTestDB(t, nil)
r := gin.New()
RegisterBusiness(r, db)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/licenses/2/instance-credentials", nil))
if w.Code != 401 {
t.Fatal("unauthenticated access")
}
}
type credentialsAuditDB struct {
*dashboardDB
fail bool
audited bool
}
func (d *credentialsAuditDB) Connect(context.Context) (driver.Conn, error) { return d, nil }
func (d *credentialsAuditDB) ExecContext(_ context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
if !strings.Contains(query, "instance.credentials.viewed") || len(args) != 3 || args[2].Value != "{}" {
return nil, errors.New("unexpected audit")
}
d.audited = true
if d.fail {
return nil, errors.New("audit unavailable")
}
return driver.RowsAffected(1), nil
}
func TestInstanceCredentialsAuditBeforeDisclosure(t *testing.T) {
key := bytes.Repeat([]byte{1}, 32)
encrypted, _ := sealInstanceSecret(key, "instance-a", "test-secret")
for _, fail := range []bool{false, true} {
stub := &credentialsAuditDB{dashboardDB: &dashboardDB{t: t, queries: []dashboardQuery{{sql: `SELECT i.instance_id,l.license_key,i.secret_encrypted FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.license_id=?`, args: []any{int64(2)}, rows: [][]driver.Value{{"instance-a", "test-license", encrypted}}}}}, fail: fail}
db := sql.OpenDB(stub)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/", nil)
c.Params = gin.Params{{Key: "id", Value: "2"}}
c.Set("admin_id", uint64(1))
(&BusinessAPI{db: db, credentialEncryptionKey: key}).instanceCredentials(c)
db.Close()
if !stub.audited {
t.Fatal("missing audit")
}
if fail {
if w.Code != 500 || strings.Contains(w.Body.String(), "test-secret") {
t.Fatal("disclosed before audit")
}
} else if w.Code != 200 || !strings.Contains(w.Body.String(), "test-secret") || w.Header().Get("Cache-Control") != "no-store" {
t.Fatal("read failed")
}
}
}

View File

@@ -4,7 +4,7 @@
## 交付与激活 ## 交付与激活
管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和仅首次展示的 secret。secret 无法从后台恢复;它不是用完即失效的口令,激活后仍用于心跳与下载,必须安全持久化。不得跨安装复制共享凭据。 管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和secret。配置加密留存后管理员可重复查看并导出;旧实例仅存哈希时无法恢复;它不是用完即失效的口令,激活后仍用于心跳与下载,必须安全持久化。不得跨安装复制共享凭据。
管理台操作:创建客户和产品 → 签发授权 → 在该授权行点击“实例” → “创建实例并获取激活凭据” → 安全保存并交付三个字段。当前每条授权只允许一个实例。 管理台操作:创建客户和产品 → 签发授权 → 在该授权行点击“实例” → “创建实例并获取激活凭据” → 安全保存并交付三个字段。当前每条授权只允许一个实例。
@@ -14,7 +14,7 @@
### 授权文件导入(交付格式 v1) ### 授权文件导入(交付格式 v1)
创建实例成功后,管理员可在当前凭据窗口点击“导出授权文件”,下载 UTF-8 JSON(文件名 license-{instance_id}.license.json)。仅首次展示期间可导出;已有实例无法恢复 secret 或重新导出。文件包含明文实例凭据,须经安全渠道交付,导入后移入受保护存储并妥善处理原下载文件。 创建实例成功后,管理员可在当前凭据窗口点击“导出授权文件”,下载 UTF-8 JSON(文件名 license-{instance_id}.license.json)。加密留存的实例可由管理员重复查看并导出;旧实例或未配置留存时仅首次返回。文件包含明文实例凭据,须经安全渠道交付,导入后移入受保护存储并妥善处理原下载文件。
```json ```json
{"format":"yhy-license-activation","version":1,"api_base_url":"https://license.yihuiyong.cn","instance_id":"实例UUID","license_key":"授权密钥","secret":"实例激活密钥"} {"format":"yhy-license-activation","version":1,"api_base_url":"https://license.yihuiyong.cn","instance_id":"实例UUID","license_key":"授权密钥","secret":"实例激活密钥"}

View File

@@ -118,7 +118,7 @@ func integrationPrompt(language, mode string) string {
默认授权平台根地址:%s。将它作为 SDK 的默认值,同时允许部署通过 LICENSE_API_BASE_URL 覆盖;配置为根地址,不要附加 /api/v1,不要在业务代码中散落硬编码 URL。 默认授权平台根地址:%s。将它作为 SDK 的默认值,同时允许部署通过 LICENSE_API_BASE_URL 覆盖;配置为根地址,不要附加 /api/v1,不要在业务代码中散落硬编码 URL。
首次设置由管理员在“授权 → 实例 → 创建实例并获取激活凭据”交付 instance_id、license_key、secret。支持管理台导出的 .license.json 文件导入,严格遵循 protocol.md“授权文件导入”的格式、大小限制、地址确认/允许列表和受保护存储要求;导入后仍需在线激活与验签,不能作为离线授权证书。UI 字段统一为“实例 ID”“授权码”“激活密钥”。实例 ID 不是数据库数字 ID;授权码是后台授权密钥;secret 仅首次展示但持续用于心跳和下载。公钥通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,丢失 secret 没有找回接口。 首次设置由管理员在“授权 → 实例 → 创建实例并获取激活凭据”交付 instance_id、license_key、secret。支持管理台导出的 .license.json 文件导入,严格遵循 protocol.md“授权文件导入”的格式、大小限制、地址确认/允许列表和受保护存储要求;导入后仍需在线激活与验签,不能作为离线授权证书。UI 字段统一为“实例 ID”“授权码”“激活密钥”。实例 ID 不是数据库数字 ID;授权码是后台授权密钥;secret 持续用于心跳和下载;配置加密留存后可重复查看,旧实例无法从哈希恢复。公钥通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,旧实例丢失 secret 无法恢复。
实现激活 POST /api/v1/activation/instances/{instance_id},提交 license_key、secret 和 Idempotency-Key;实现心跳 POST /api/v1/instances/{instance_id}/heartbeat,提交 secret、RFC3339 UTC client_time 和 Idempotency-Key。 实现激活 POST /api/v1/activation/instances/{instance_id},提交 license_key、secret 和 Idempotency-Key;实现心跳 POST /api/v1/instances/{instance_id}/heartbeat,提交 secret、RFC3339 UTC client_time 和 Idempotency-Key。

View File

@@ -9,7 +9,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
const RequiredSchemaVersion = 10 const RequiredSchemaVersion = 11
func RegisterReadiness(r *gin.Engine, db *sql.DB) { func RegisterReadiness(r *gin.Engine, db *sql.DB) {
r.GET("/api/v1/health/ready", func(c *gin.Context) { r.GET("/api/v1/health/ready", func(c *gin.Context) {

View File

@@ -0,0 +1 @@
ALTER TABLE license_instances DROP COLUMN secret_encrypted;

View File

@@ -0,0 +1 @@
ALTER TABLE license_instances ADD COLUMN secret_encrypted VARBINARY(256) NULL;

View File

@@ -27,3 +27,5 @@ go run ./cmd/migrate -dsn "$MIGRATION_DSN" -version 12 force
On 2026-09-30, a dedicated MySQL 8.0 container was used to verify an empty database up/down cycle and an intentionally invalid migration: failure left version 2 dirty, normal `up` was blocked, and explicit force to the last known-good version restored clean metadata. The probe migrations and container were removed after the test. Version 3 adds transactional license operation idempotency records for revoke/renew; it must be applied explicitly after version 2. No placeholder SQL is considered an executed business migration; formal entitlement schemas and CI database integration remain T04/T03 acceptance work. On 2026-09-30, a dedicated MySQL 8.0 container was used to verify an empty database up/down cycle and an intentionally invalid migration: failure left version 2 dirty, normal `up` was blocked, and explicit force to the last known-good version restored clean metadata. The probe migrations and container were removed after the test. Version 3 adds transactional license operation idempotency records for revoke/renew; it must be applied explicitly after version 2. No placeholder SQL is considered an executed business migration; formal entitlement schemas and CI database integration remain T04/T03 acceptance work.
Schema 10 adds unique administrator usernames. Existing accounts become `admin-{id}` and retain their passwords; login requests must send `username` instead of `email`. Run migrations before starting the current server or `admin-init`. Schema 10 adds unique administrator usernames. Existing accounts become `admin-{id}` and retain their passwords; login requests must send `username` instead of `email`. Run migrations before starting the current server or `admin-init`.
Schema 11 adds nullable `license_instances.secret_encrypted`. Apply before API startup. Configure `LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE` as an absolute path to an independent 32-byte raw random key. Mount read-only, back up securely with the database, and never commit it. Missing key preserves first-return-only creation. Existing hashes cannot recover secrets. Losing/changing the key makes ciphertext unreadable; rotation is not implemented. Down migration deletes retained ciphertext and requires backup and confirmation.

View File

@@ -54,3 +54,9 @@ go run ./cmd/admin-init -username admin -email admin@example.test -password 'YOU
``` ```
初始化命令按邮箱识别已有账户,用户名冲突将报错,不会重置另一个账户。重新初始化会撤销该账户的旧会话。已有部署只执行迁移即可,不需要重置密码。原始业务数据库没有在本次开发中迁移;本地隔离数据库的既有账号为 `admin-1`,密码保持 `123456`。 初始化命令按邮箱识别已有账户,用户名冲突将报错,不会重置另一个账户。重新初始化会撤销该账户的旧会话。已有部署只执行迁移即可,不需要重置密码。原始业务数据库没有在本次开发中迁移;本地隔离数据库的既有账号为 `admin-1`,密码保持 `123456`。
## 客户端凭据与在线状态
Schema 11 后,配置 LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE(独立 32 字节原始随机密钥,只读挂载、权限 0600)可加密保存新实例 secret。管理员可重复查看及导出 JSON,读取记录 instance.credentials.viewed 审计事件并返回 no-store;凭据只在当前视图,不写浏览器持久存储。旧实例无法恢复,未配置时仍仅首次返回。加密密钥须安全备份,不可随意替换,不提供自动轮换。
激活状态和连接状态分别展示;最近 3 分钟收到心跳为在线,超时为离线,无心跳为从未上报,未来时间为未知。点击刷新更新状态,离线不表示授权失效。

View File

@@ -35,7 +35,7 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权
## 首次激活交付与客户端字段 ## 首次激活交付与客户端字段
管理员创建客户/产品并签发授权后,在“License 授权 → 实例 → 创建实例并获取激活凭据”预置实例。授权码对应 license_key(授权密钥),实例 ID 对应 instance_id(UUID),激活密钥对应 secret。平台目前每条授权只绑定一个实例。secret 只在创建响应及当前窗口展示,数据库保存哈希,关闭后无法恢复;该凭据激活后仍用于心跳和下载。创建超时先刷新实例列表核实,不自动重试。丢失凭据需冻结旧实例、撤销旧授权,再签发新授权交付新实例;旧离线租约最多仍可生效 14 天。客户端不应让用户填写管理员密码或签名私钥,公钥通过受控渠道预置;激活后加载受保护状态,不要求每次启动填写。 管理员创建客户/产品并签发授权后,在“License 授权 → 实例 → 创建实例并获取激活凭据”预置实例。授权码对应 license_key(授权密钥),实例 ID 对应 instance_id(UUID),激活密钥对应 secret。平台目前每条授权只绑定一个实例。配置凭据加密密钥后,新实例同时保存密文与验证哈希,管理员可重复查看和下载 JSON;旧实例或未配置时仅存哈希,无法恢复;该凭据激活后仍用于心跳和下载。创建超时先刷新实例列表核实,不自动重试。丢失凭据需冻结旧实例、撤销旧授权,再签发新授权交付新实例;旧离线租约最多仍可生效 14 天。客户端不应让用户填写管理员密码或签名私钥,公钥通过受控渠道预置;激活后加载受保护状态,不要求每次启动填写。
## 授权文件导出与导入 ## 授权文件导出与导入

View File

@@ -22,11 +22,12 @@ export async function deleteProduct(id:number) { return api.delete(`/products/${
export type License = { id:number; license_key:string; customer_id:number; customer_name:string; product_id:number; product_name:string; product_code:string; status:'active'|'scheduled'|'expired'|'revoked'|string; starts_at:string; expires_at:string; created_at:string } export type License = { id:number; license_key:string; customer_id:number; customer_name:string; product_id:number; product_name:string; product_code:string; status:'active'|'scheduled'|'expired'|'revoked'|string; starts_at:string; expires_at:string; created_at:string }
export async function listLicenses(params?:Record<string,string|number>) { return api.get<{data:License[];meta:{page:number;page_size:number;total:number}}>('/licenses',{params}) } export async function listLicenses(params?:Record<string,string|number>) { return api.get<{data:License[];meta:{page:number;page_size:number;total:number}}>('/licenses',{params}) }
export async function issueLicense(value:{customer_id:number;product_id:number;starts_at:string;expires_at:string}, idempotencyKey:string) { return api.post('/licenses',value,{headers:{'Idempotency-Key':idempotencyKey}}) } export async function issueLicense(value:{customer_id:number;product_id:number;starts_at:string;expires_at:string}, idempotencyKey:string) { return api.post('/licenses',value,{headers:{'Idempotency-Key':idempotencyKey}}) }
export type LicenseInstance = { id:number; instance_id:string; license_id:number; customer_id:number; product_id:number; status:string; activated_at?:string; certificate_version?:string; created_at:string; last_seen_at?:string; lease_expires_at?:string; freeze_state:string; observed_state:string; entitlement_state:string } export type LicenseInstance = { online_state?:'online'|'offline'|'never_seen'|'unknown'; id:number; instance_id:string; license_id:number; customer_id:number; product_id:number; status:string; activated_at?:string; certificate_version?:string; created_at:string; last_seen_at?:string; lease_expires_at?:string; freeze_state:string; observed_state:string; entitlement_state:string }
export async function setInstanceFrozen(instanceID:string,frozen:boolean,key:string) { return api.post(`/instances/${instanceID}/freeze`,{frozen},{headers:{'Idempotency-Key':key}}) } export async function setInstanceFrozen(instanceID:string,frozen:boolean,key:string) { return api.post(`/instances/${instanceID}/freeze`,{frozen},{headers:{'Idempotency-Key':key}}) }
export async function listLicenseInstances(id:number) { return api.get<{data:LicenseInstance[]}>(`/licenses/${id}/instances`) } export async function listLicenseInstances(id:number) { return api.get<{data:LicenseInstance[]}>(`/licenses/${id}/instances`) }
export async function getLicense(id:number) { return api.get<{data:License}>(`/licenses/${id}`) } export async function getLicense(id:number) { return api.get<{data:License}>(`/licenses/${id}`) }
export async function revokeLicense(id:number,idempotencyKey:string) { return api.post(`/licenses/${id}/revoke`,{}, {headers:{'Idempotency-Key':idempotencyKey}}) } export async function revokeLicense(id:number,idempotencyKey:string) { return api.post(`/licenses/${id}/revoke`,{}, {headers:{'Idempotency-Key':idempotencyKey}}) }
export async function renewLicense(id:number,expires_at:string,idempotencyKey:string) { return api.post(`/licenses/${id}/renew`,{expires_at},{headers:{'Idempotency-Key':idempotencyKey}}) } export async function renewLicense(id:number,expires_at:string,idempotencyKey:string) { return api.post(`/licenses/${id}/renew`,{expires_at},{headers:{'Idempotency-Key':idempotencyKey}}) }
export async function provisionLicenseInstance(id:number) { return api.post<{data:{id:number;instance_id:string;license_id:number;status:string;secret:string}}>(`/licenses/${id}/instances`,{}) } export async function getInstanceCredentials(id:number) { return api.get<{data:{instance_id:string;license_key:string;secret:string}}>(`/licenses/${id}/instance-credentials`) }
export async function provisionLicenseInstance(id:number) { return api.post<{data:{id:number;instance_id:string;license_id:number;status:string;secret:string};credentials_retained:boolean}>(`/licenses/${id}/instances`,{}) }

View File

@@ -1,7 +1,7 @@
import { beforeEach, expect, it, vi } from 'vitest' import { beforeEach, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils' import { flushPromises, mount } from '@vue/test-utils'
import ElementPlus, { ElMessageBox } from 'element-plus' import ElementPlus, { ElMessageBox } from 'element-plus'
const api=vi.hoisted(()=>({getLicense:vi.fn(),provisionLicenseInstance:vi.fn()})) const api=vi.hoisted(()=>({getLicense:vi.fn(),provisionLicenseInstance:vi.fn(),getInstanceCredentials:vi.fn()}))
vi.mock('../api',()=>api) vi.mock('../api',()=>api)
import Panel from './InstanceProvisionPanel.vue' import Panel from './InstanceProvisionPanel.vue'
beforeEach(()=>{vi.restoreAllMocks();vi.resetAllMocks();vi.spyOn(ElMessageBox,'confirm').mockResolvedValue('confirm' as Awaited<ReturnType<typeof ElMessageBox.confirm>>);api.getLicense.mockResolvedValue({data:{data:{license_key:'test-license'}}});api.provisionLicenseInstance.mockResolvedValue({data:{data:{instance_id:'test-instance',secret:'test-secret'}}})}) beforeEach(()=>{vi.restoreAllMocks();vi.resetAllMocks();vi.spyOn(ElMessageBox,'confirm').mockResolvedValue('confirm' as Awaited<ReturnType<typeof ElMessageBox.confirm>>);api.getLicense.mockResolvedValue({data:{data:{license_key:'test-license'}}});api.provisionLicenseInstance.mockResolvedValue({data:{data:{instance_id:'test-instance',secret:'test-secret'}}})})
@@ -10,9 +10,14 @@ it('creates and displays first-return credentials, without another creation entr
await w.get('button').trigger('click');await flushPromises() await w.get('button').trigger('click');await flushPromises()
expect(api.provisionLicenseInstance).toHaveBeenCalledWith(7) expect(api.provisionLicenseInstance).toHaveBeenCalledWith(7)
expect(w.text()).toContain('test-license');expect(w.text()).toContain('test-instance');expect(w.text()).toContain('test-secret');expect(w.emitted('created')).toHaveLength(1) expect(w.text()).toContain('test-license');expect(w.text()).toContain('test-instance');expect(w.text()).toContain('test-secret');expect(w.emitted('created')).toHaveLength(1)
expect(w.findAll('button').map(b=>b.text())).toEqual(['导出授权文件']);w.unmount() expect(w.findAll('button').map(b=>b.text())).toEqual(['导出授权文件','隐藏凭据']);w.unmount()
const reopened=mount(Panel,{props:{licenseId:7,hasInstance:true,ready:true},global:{plugins:[ElementPlus]}}) const reopened=mount(Panel,{props:{licenseId:7,hasInstance:true,ready:true},global:{plugins:[ElementPlus]}})
expect(reopened.get('button').attributes('disabled')).toBeDefined();expect(reopened.text()).not.toContain('test-secret');reopened.unmount() expect(reopened.get('button').attributes('disabled')).toBeUndefined();expect(reopened.text()).not.toContain('test-secret');
api.getInstanceCredentials.mockResolvedValue({data:{data:{instance_id:'saved-instance',license_key:'saved-license',secret:'saved-secret'}}})
await reopened.get('button').trigger('click');await flushPromises()
expect(api.getInstanceCredentials).toHaveBeenCalledWith(7);expect(reopened.text()).toContain('saved-secret')
await reopened.findAll('button').find(b=>b.text()==='隐藏凭据')!.trigger('click')
expect(reopened.text()).not.toContain('saved-secret');reopened.unmount()
}) })
it('reports uncertain creation without automatically retrying',async()=>{ it('reports uncertain creation without automatically retrying',async()=>{
api.provisionLicenseInstance.mockRejectedValue(new Error('请求超时')) api.provisionLicenseInstance.mockRejectedValue(new Error('请求超时'))

View File

@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { ref } from 'vue'
import { ElMessageBox } from 'element-plus' import { ElMessageBox } from 'element-plus'
import { getLicense, provisionLicenseInstance } from '../api' import { getLicense, provisionLicenseInstance, getInstanceCredentials } from '../api'
import { downloadLicenseFile } from '../license-file' import { downloadLicenseFile } from '../license-file'
const props = defineProps<{licenseId:number;hasInstance:boolean;ready:boolean}>() const props = defineProps<{licenseId:number;hasInstance:boolean;ready:boolean}>()
const emit = defineEmits<{created:[]}>() const emit = defineEmits<{created:[]}>()
@@ -14,16 +14,27 @@ function exportFile() {
catch (e) { exportError.value = e instanceof Error ? e.message : '导出失败,请重试' } catch (e) { exportError.value = e instanceof Error ? e.message : '导出失败,请重试' }
} }
const credentials = ref<{instance_id:string;license_key:string;secret:string}|null>(null) const credentials = ref<{instance_id:string;license_key:string;secret:string}|null>(null)
const retained = ref(false)
async function viewCredentials() {
if(busy.value || !props.ready) return
try { await ElMessageBox.confirm('此操作将显示完整激活密钥并记录审计事件,请确保当前屏幕环境安全。','查看客户端激活凭据') } catch { return }
busy.value=true;error.value=''
try { credentials.value=(await getInstanceCredentials(props.licenseId)).data.data;retained.value=true }
catch(e) { error.value=e instanceof Error?e.message:'读取凭据失败' }
finally { busy.value=false }
}
async function create() { async function create() {
if(busy.value || props.hasInstance || !props.ready || credentials.value || error.value) return if(busy.value || props.hasInstance || !props.ready || credentials.value || error.value) return
try { await ElMessageBox.confirm('每条授权只能绑定一个实例。激活密钥仅在创建成功时显示,请立即通过安全渠道保存并交付。确认创建?','创建客户端实例') } catch { return } try { await ElMessageBox.confirm('每条授权只能绑定一个实例。配置凭据加密存储后可重复查看;未配置时仅首次返回,请安全保存并交付。确认创建?','创建客户端实例') } catch { return }
busy.value=true;error.value='' busy.value=true;error.value=''
try { try {
const license=(await getLicense(props.licenseId)).data.data const license=(await getLicense(props.licenseId)).data.data
const result=(await provisionLicenseInstance(props.licenseId)).data.data const response=(await provisionLicenseInstance(props.licenseId)).data
const result=response.data
retained.value=response.credentials_retained===true
credentials.value={instance_id:result.instance_id,license_key:license.license_key,secret:result.secret} credentials.value={instance_id:result.instance_id,license_key:license.license_key,secret:result.secret}
emit('created') emit('created')
} catch(e) { error.value=(e instanceof Error?e.message:'创建失败')+'。若请求超时,请先刷新实例列表确认是否已创建;密钥无法再次获取,请勿反复创建。' } } catch(e) { error.value=(e instanceof Error?e.message:'创建失败')+'。若请求超时,请先刷新实例列表确认是否已创建;已保留凭据的实例可通过查看入口获取,请勿反复创建。' }
finally { busy.value=false } finally { busy.value=false }
} }
</script> </script>
@@ -31,18 +42,20 @@ async function create() {
<section class="data-section"> <section class="data-section">
<h3>客户端激活凭据</h3> <h3>客户端激活凭据</h3>
<p>授权码就是授权密钥(license_key)。实例 ID 和激活密钥(secret)由平台创建实例时生成,每条授权仅绑定一个实例。</p> <p>授权码就是授权密钥(license_key)。实例 ID 和激活密钥(secret)由平台创建实例时生成,每条授权仅绑定一个实例。</p>
<el-button v-if="!credentials" type="primary" :loading="busy" :disabled="!ready||hasInstance||!!error" @click="create">创建实例并获取激活凭据</el-button> <el-button v-if="!credentials&&!hasInstance" type="primary" :loading="busy" :disabled="!ready||hasInstance||!!error" @click="create">创建实例并获取激活凭据</el-button>
<p v-if="hasInstance&&!credentials" class="subheading">已有实例的激活密钥无法再次查看。若未安全保存,请由管理员冻结旧实例、撤销旧授权,再签发新授权并交付新实例凭据;当前不支持密钥找回或轮换。</p> <el-button v-if="hasInstance&&!credentials" type="primary" :loading="busy" :disabled="!ready" @click="viewCredentials">查看客户端激活凭据</el-button>
<p v-if="hasInstance&&!credentials" class="subheading">已加密保留的凭据可重复查看及下载。旧实例仅存哈希,无法恢复;此类实例需使用原始交付文件,或冻结旧实例、撤销旧授权后重新签发。</p>
<p v-if="error" class="error" role="alert">{{error}}</p> <p v-if="error" class="error" role="alert">{{error}}</p>
<template v-if="credentials"> <template v-if="credentials">
<p role="status">实例已创建。请立即安全保存下列凭据,关闭窗口后不再显示激活密钥。</p> <p role="status">请安全保存和交付下列凭据。{{retained?'凭据已加密保留,可再次查看。':'未加密保留,关闭后无法再次获取。'}}</p>
<dl class="license-detail"><dt>实例 ID(instance_id)</dt><dd class="license-code">{{credentials.instance_id}}</dd><dt>授权码(license_key)</dt><dd class="license-code">{{credentials.license_key}}</dd><dt>激活密钥(secret)</dt><dd class="license-code">{{credentials.secret}}</dd></dl> <dl class="license-detail"><dt>实例 ID(instance_id)</dt><dd class="license-code">{{credentials.instance_id}}</dd><dt>授权码(license_key)</dt><dd class="license-code">{{credentials.license_key}}</dd><dt>激活密钥(secret)</dt><dd class="license-code">{{credentials.secret}}</dd></dl>
<label for="license-export-base-url">授权文件中的授权中心地址</label> <label for="license-export-base-url">授权文件中的授权中心地址</label>
<el-input id="license-export-base-url" v-model="baseURL" placeholder="https://license.yihuiyong.cn" /> <el-input id="license-export-base-url" v-model="baseURL" placeholder="https://license.yihuiyong.cn" />
<el-button type="primary" @click="exportFile">导出授权文件</el-button> <el-button type="primary" @click="exportFile">导出授权文件</el-button>
<p v-if="exportError" class="error" role="alert">{{ exportError }}</p> <p v-if="exportError" class="error" role="alert">{{ exportError }}</p>
<p>导出的 .license.json 含激活密钥,请安全交付。客户端需支持本文件格式,导入后在线激活并获取运行租约;文件本身不代表授权有效。关闭此窗口后无法再次导出包含密钥的文件。</p> <el-button @click="credentials=null">隐藏凭据</el-button>
<p>默认授权中心:https://license.yihuiyong.cn;私有部署填写实际 HTTPS 根地址。密钥仅首次展示,但客户端激活后仍需安全保存用于心跳和下载;不要放入日志、截图或普通工单。生产验签公钥应由开发团队预置。</p> <p>导出的 .license.json 含激活密钥,请安全交付。客户端需支持本文件格式,导入后在线激活并获取运行租约;文件本身不代表授权有效。已加密保留的凭据可重新查看并导出。</p>
<p>默认授权中心:https://license.yihuiyong.cn;私有部署填写实际 HTTPS 根地址。客户端激活后仍需安全保存密钥用于心跳和下载;不要放入日志、截图或普通工单。生产验签公钥应由开发团队预置。</p>
</template> </template>
</section> </section>
</template> </template>

View File

@@ -121,7 +121,7 @@ onMounted(() => { checkConnection(); checkSession() })
<section v-if="pageView==='licenses'" id="license-issue" class="data-section"><form class="filters" @submit.prevent="licensePage=1;router.replace({query:{...(route.query),q:licenseQuery||undefined}});refresh()"><input v-model="licenseQuery" placeholder="搜索客户或 License"/><select v-model="licenseStatus" @change="router.replace({query:{...(route.query),status:licenseStatus||undefined}})"><option value="">全部状态</option><option value="active">有效</option><option value="expiring">即将到期</option><option value="pending">未开始</option><option value="expired">已到期</option><option value="revoked">已撤销</option></select><button class="search-button">搜索</button></form><div class="section-heading"><div><h2>期限授权</h2><p>共 {{ licenseTotal }} 条,签发后通过“实例”创建并交付客户端激活凭据</p></div><div class="inline-form license-form"><el-select v-model="issueForm.customer_id" placeholder="选择客户"><el-option v-for="item in customers" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status !== 'active'"/></el-select><el-select v-model="issueForm.product_id" placeholder="选择产品"><el-option v-for="item in products" :key="item.id" :label="item.name" :value="item.id" :disabled="!item.active"/></el-select><el-date-picker v-model="issueForm.starts_at" type="datetime" value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="开始时间" aria-label="开始时间"/><el-date-picker v-model="issueForm.expires_at" type="datetime" value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="结束时间" aria-label="结束时间"/><el-button type="primary" :loading="issuing" @click="issue">签发授权</el-button></div></div><div class="business-table"><el-table :data="licenses" v-loading="loading" empty-text="暂无授权"><el-table-column prop="license_key" label="授权密钥" min-width="230"/><el-table-column prop="customer_name" label="客户"/><el-table-column prop="product_name" label="产品"/><el-table-column prop="status" label="状态"/><el-table-column label="开始(本地时间)" min-width="190"><template #default="scope">{{ formatDateTime(scope.row.starts_at) }}</template></el-table-column><el-table-column label="结束(本地时间)" min-width="190"><template #default="scope">{{ formatDateTime(scope.row.expires_at) }}</template></el-table-column><el-table-column label="操作" width="250"><template #default="scope"><el-button link @click="showDetail(scope.row.id)">详情</el-button><el-button link @click="showInstances(scope.row.id)">实例</el-button><el-button link @click="renew(scope.row)" :disabled="scope.row.status === 'revoked'">续期</el-button><el-button link type="danger" @click="revoke(scope.row.id)" :disabled="scope.row.status === 'revoked'">撤销</el-button></template></el-table-column></el-table><el-pagination v-model:current-page="licensePage" :total="licenseTotal" :page-size="20" layout="prev, pager, next" @current-change="refresh"/></div></section> <section v-if="pageView==='licenses'" id="license-issue" class="data-section"><form class="filters" @submit.prevent="licensePage=1;router.replace({query:{...(route.query),q:licenseQuery||undefined}});refresh()"><input v-model="licenseQuery" placeholder="搜索客户或 License"/><select v-model="licenseStatus" @change="router.replace({query:{...(route.query),status:licenseStatus||undefined}})"><option value="">全部状态</option><option value="active">有效</option><option value="expiring">即将到期</option><option value="pending">未开始</option><option value="expired">已到期</option><option value="revoked">已撤销</option></select><button class="search-button">搜索</button></form><div class="section-heading"><div><h2>期限授权</h2><p>共 {{ licenseTotal }} 条,签发后通过“实例”创建并交付客户端激活凭据</p></div><div class="inline-form license-form"><el-select v-model="issueForm.customer_id" placeholder="选择客户"><el-option v-for="item in customers" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status !== 'active'"/></el-select><el-select v-model="issueForm.product_id" placeholder="选择产品"><el-option v-for="item in products" :key="item.id" :label="item.name" :value="item.id" :disabled="!item.active"/></el-select><el-date-picker v-model="issueForm.starts_at" type="datetime" value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="开始时间" aria-label="开始时间"/><el-date-picker v-model="issueForm.expires_at" type="datetime" value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="结束时间" aria-label="结束时间"/><el-button type="primary" :loading="issuing" @click="issue">签发授权</el-button></div></div><div class="business-table"><el-table :data="licenses" v-loading="loading" empty-text="暂无授权"><el-table-column prop="license_key" label="授权密钥" min-width="230"/><el-table-column prop="customer_name" label="客户"/><el-table-column prop="product_name" label="产品"/><el-table-column prop="status" label="状态"/><el-table-column label="开始(本地时间)" min-width="190"><template #default="scope">{{ formatDateTime(scope.row.starts_at) }}</template></el-table-column><el-table-column label="结束(本地时间)" min-width="190"><template #default="scope">{{ formatDateTime(scope.row.expires_at) }}</template></el-table-column><el-table-column label="操作" width="250"><template #default="scope"><el-button link @click="showDetail(scope.row.id)">详情</el-button><el-button link @click="showInstances(scope.row.id)">实例</el-button><el-button link @click="renew(scope.row)" :disabled="scope.row.status === 'revoked'">续期</el-button><el-button link type="danger" @click="revoke(scope.row.id)" :disabled="scope.row.status === 'revoked'">撤销</el-button></template></el-table-column></el-table><el-pagination v-model:current-page="licensePage" :total="licenseTotal" :page-size="20" layout="prev, pager, next" @current-change="refresh"/></div></section>
<ReleasesPanel v-if="pageView==='releases'" :products="products"/> <ReleasesPanel v-if="pageView==='releases'" :products="products"/>
<OrdersPanel v-if="pageView==='orders'" :customers="customers" :products="products" @issued="refresh"/> <OrdersPanel v-if="pageView==='orders'" :customers="customers" :products="products" @issued="refresh"/>
<AdminsPanel v-if="pageView==='admins'" :current-username="adminEmail"/><IntegrationPanel v-if="pageView==='integration'"/><AuditPanel v-if="pageView==='audit'"/><SettingsPanel v-if="pageView==='settings'" @saved="siteSettings=$event"/><el-dialog v-model="renewalOpen" title="续期授权" width="min(480px, 95vw)" :close-on-click-modal="!renewing" :close-on-press-escape="!renewing" :show-close="!renewing"><template v-if="renewalLicense"><p>当前到期时间:{{ formatDateTime(renewalLicense.expires_at) }}</p><label for="renewal-date">新的到期时间(本地时间)</label><el-date-picker id="renewal-date" v-model="renewalDate" type="datetime" format="YYYY-MM-DD HH:mm:ss" placeholder="选择新的到期日期与时间" aria-label="新的到期时间" :disabled-date="disabledRenewalDate" :disabled="renewing" style="width:100%;margin-top:8px"/><p class="subheading">请选择晚于当前到期时间的日期和时间。</p><p v-if="renewalError" class="error" role="alert">{{ renewalError }}</p></template><template #footer><el-button :disabled="renewing" @click="renewalOpen=false">取消</el-button><el-button type="primary" :loading="renewing" @click="submitRenewal">确认续期</el-button></template></el-dialog><el-dialog v-model="detailOpen" title="授权详情" width="min(520px, 95vw)"><div v-loading="detailLoading"><p v-if="detailError" class="error" role="alert">{{detailError}}</p><dl v-if="detail" class="license-detail"><dt>License 密钥</dt><dd class="license-code">{{detail.license_key}}</dd><dt>客户</dt><dd>{{detail.customer_name}}</dd><dt>产品</dt><dd>{{detail.product_name}}</dd><dt>类型</dt><dd>期限授权</dd><dt>开始时间</dt><dd>{{formatDateTime(detail.starts_at)}}</dd><dt>到期时间</dt><dd>{{formatDateTime(detail.expires_at)}}</dd><dt>状态</dt><dd>{{detail.status}}</dd></dl><el-button v-if="detail" @click="showInstances(detail.id)">查看实例 / 冻结管理</el-button></div></el-dialog><el-drawer v-model="instanceDrawer" title="授权实例与激活凭据" size="min(100%, 680px)"><InstanceProvisionPanel v-if="instanceDrawer&&selectedLicenseID!==null" :key="selectedLicenseID" :license-id="selectedLicenseID" :has-instance="instances.length>0" :ready="!instancesLoading&&!instanceError" @created="showInstances(selectedLicenseID!)"/><el-button :loading="instancesLoading" @click="selectedLicenseID !== null && showInstances(selectedLicenseID)">刷新状态</el-button><p v-if="instanceError" class="error">{{ instanceError }}</p><div class="business-table"><el-table :data="instances" v-loading="instancesLoading" empty-text="未绑定实例"><el-table-column prop="instance_id" label="实例 ID" min-width="290"/><el-table-column prop="status" label="激活状态"/><el-table-column prop="certificate_version" label="证书版本"/><el-table-column label="激活时间" min-width="200"><template #default="scope">{{ formatDateTime(scope.row.activated_at) }}</template></el-table-column><el-table-column label="最后在线" min-width="200"><template #default="scope">{{ formatDateTime(scope.row.last_seen_at) }}</template></el-table-column><el-table-column label="租约到期" min-width="200"><template #default="scope">{{ formatDateTime(scope.row.lease_expires_at) }}</template></el-table-column><el-table-column prop="freeze_state" label="冻结状态"/><el-table-column prop="entitlement_state" label="授权状态"/><el-table-column prop="observed_state" label="已传播状态"/><el-table-column label="管理" fixed="right" width="90"><template #default="scope"><el-button link :type="scope.row.freeze_state === 'frozen' ? 'primary' : 'danger'" :loading="changingInstance === scope.row.instance_id" :disabled="!!changingInstance" @click="changeFreeze(scope.row)">{{ scope.row.freeze_state === 'frozen' ? '恢复' : '冻结' }}</el-button></template></el-table-column></el-table></div></el-drawer> <AdminsPanel v-if="pageView==='admins'" :current-username="adminEmail"/><IntegrationPanel v-if="pageView==='integration'"/><AuditPanel v-if="pageView==='audit'"/><SettingsPanel v-if="pageView==='settings'" @saved="siteSettings=$event"/><el-dialog v-model="renewalOpen" title="续期授权" width="min(480px, 95vw)" :close-on-click-modal="!renewing" :close-on-press-escape="!renewing" :show-close="!renewing"><template v-if="renewalLicense"><p>当前到期时间:{{ formatDateTime(renewalLicense.expires_at) }}</p><label for="renewal-date">新的到期时间(本地时间)</label><el-date-picker id="renewal-date" v-model="renewalDate" type="datetime" format="YYYY-MM-DD HH:mm:ss" placeholder="选择新的到期日期与时间" aria-label="新的到期时间" :disabled-date="disabledRenewalDate" :disabled="renewing" style="width:100%;margin-top:8px"/><p class="subheading">请选择晚于当前到期时间的日期和时间。</p><p v-if="renewalError" class="error" role="alert">{{ renewalError }}</p></template><template #footer><el-button :disabled="renewing" @click="renewalOpen=false">取消</el-button><el-button type="primary" :loading="renewing" @click="submitRenewal">确认续期</el-button></template></el-dialog><el-dialog v-model="detailOpen" title="授权详情" width="min(520px, 95vw)"><div v-loading="detailLoading"><p v-if="detailError" class="error" role="alert">{{detailError}}</p><dl v-if="detail" class="license-detail"><dt>License 密钥</dt><dd class="license-code">{{detail.license_key}}</dd><dt>客户</dt><dd>{{detail.customer_name}}</dd><dt>产品</dt><dd>{{detail.product_name}}</dd><dt>类型</dt><dd>期限授权</dd><dt>开始时间</dt><dd>{{formatDateTime(detail.starts_at)}}</dd><dt>到期时间</dt><dd>{{formatDateTime(detail.expires_at)}}</dd><dt>状态</dt><dd>{{detail.status}}</dd></dl><el-button v-if="detail" @click="showInstances(detail.id)">查看实例 / 冻结管理</el-button></div></el-dialog><el-drawer v-model="instanceDrawer" title="授权实例与激活凭据" size="min(100%, 680px)"><InstanceProvisionPanel v-if="instanceDrawer&&selectedLicenseID!==null" :key="selectedLicenseID" :license-id="selectedLicenseID" :has-instance="instances.length>0" :ready="!instancesLoading&&!instanceError" @created="showInstances(selectedLicenseID!)"/><el-button :loading="instancesLoading" @click="selectedLicenseID !== null && showInstances(selectedLicenseID)">刷新状态</el-button><p class="subheading">在线表示服务端最近 3 分钟收到心跳;超时显示离线,从未心跳显示从未上报。离线不代表授权失效;状态在刷新时更新。</p><p v-if="instanceError" class="error">{{ instanceError }}</p><div class="business-table"><el-table :data="instances" v-loading="instancesLoading" empty-text="未绑定实例"><el-table-column prop="instance_id" label="实例 ID" min-width="290"/><el-table-column label="激活状态" min-width="110"><template #default="scope"><el-tag :type="scope.row.status==='activated'?'success':'info'">{{scope.row.status==='activated'?'已激活':scope.row.status==='provisioned'?'未激活':scope.row.status}}</el-tag></template></el-table-column><el-table-column label="连接状态" min-width="120"><template #default="scope"><el-tag :type="scope.row.online_state==='online'?'success':scope.row.online_state==='offline'?'warning':'info'">{{scope.row.online_state==='online'?'在线':scope.row.online_state==='offline'?'离线':scope.row.online_state==='never_seen'?'从未上报':'未知'}}</el-tag></template></el-table-column><el-table-column prop="certificate_version" label="证书版本"/><el-table-column label="激活时间" min-width="200"><template #default="scope">{{ formatDateTime(scope.row.activated_at) }}</template></el-table-column><el-table-column label="最后在线" min-width="200"><template #default="scope">{{ formatDateTime(scope.row.last_seen_at) }}</template></el-table-column><el-table-column label="租约到期" min-width="200"><template #default="scope">{{ formatDateTime(scope.row.lease_expires_at) }}</template></el-table-column><el-table-column prop="freeze_state" label="冻结状态"/><el-table-column prop="entitlement_state" label="授权状态"/><el-table-column prop="observed_state" label="已传播状态"/><el-table-column label="管理" fixed="right" width="90"><template #default="scope"><el-button link :type="scope.row.freeze_state === 'frozen' ? 'primary' : 'danger'" :loading="changingInstance === scope.row.instance_id" :disabled="!!changingInstance" @click="changeFreeze(scope.row)">{{ scope.row.freeze_state === 'frozen' ? '恢复' : '冻结' }}</el-button></template></el-table-column></el-table></div></el-drawer>
</main> </main>
</div></div> </div></div>
</template> </template>