feat: delete never-activated licenses and bundle deployment verification keys
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 14:31:15 +08:00
parent 03a3b9f6a9
commit f4b99e50cd
9 changed files with 221 additions and 12 deletions

View File

@@ -94,6 +94,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
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.GET("/licenses/:id/instance-credentials", a.instanceCredentials)
secured.DELETE("/licenses/:id", a.deleteLicense)
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

@@ -71,8 +71,14 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
return return
} }
kit := buildIntegrationKit(language, mode) kit := buildIntegrationKit(language, mode)
keys, err := a.deploymentVerificationKeys()
if err != nil {
apiError(c, 503, "keyring_unavailable", "当前部署未配置可交付的验签公钥")
return
}
files := map[string][]byte{ files := map[string][]byte{
"README.md": []byte("# 客户端接入包\n\n阅读 protocol.md、upgrade.md 与 openapi.json,将 prompt.md 提供给实现工程师。upgrade.md 说明当前可用下载能力和自动升级待建设的契约;当前没有客户端版本检查或签名升级清单。test-vectors.json 使用随机测试密钥,绝不能导入生产。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"), "README.md": []byte("# 客户端接入包\n\n阅读 protocol.md、upgrade.md 与 openapi.json,将 prompt.md 提供给实现工程师。verification-keys.md 包含当前部署验签公钥,经可信渠道核对指纹后预置;test-vectors.json 使用随机测试密钥,绝不能导入生产。upgrade.md 说明当前可用下载能力和自动升级待建设的契约;当前没有客户端版本检查或签名升级清单。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"),
"verification-keys.md": []byte(keys),
"prompt.md": []byte(kit.Prompt), "prompt.md": []byte(kit.Prompt),
"test-vectors.json": vectors, "test-vectors.json": vectors,
} }
@@ -86,7 +92,7 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
} }
var buffer bytes.Buffer var buffer bytes.Buffer
archive := zip.NewWriter(&buffer) archive := zip.NewWriter(&buffer)
for _, name := range []string{"README.md", "protocol.md", "upgrade.md", "openapi.json", "prompt.md", "test-vectors.json"} { for _, name := range []string{"README.md", "protocol.md", "upgrade.md", "openapi.json", "prompt.md", "verification-keys.md", "test-vectors.json"} {
file, err := archive.Create(name) file, err := archive.Create(name)
if err == nil { if err == nil {
_, err = file.Write(files[name]) _, err = file.Write(files[name])

View File

@@ -1,7 +1,10 @@
package httpapi package httpapi
import ( import (
"crypto/sha256"
"embed" "embed"
"encoding/hex"
"encoding/pem"
"fmt" "fmt"
"net/http" "net/http"
"strings" "strings"
@@ -135,15 +138,41 @@ func (a *BusinessAPI) integrationKit(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": buildIntegrationKit(language, mode)}) c.JSON(http.StatusOK, gin.H{"data": buildIntegrationKit(language, mode)})
} }
func (a *BusinessAPI) deploymentVerificationKeys() (string, error) {
if a.keyring == nil {
return "", fmt.Errorf("keyring unavailable")
}
var b strings.Builder
b.WriteString("## 当前部署验签公钥\n\n以下公钥来自当前服务端已配置的 keyring,不是 test-vectors.json 中的随机测试密钥。请经可信的管理员交付渠道核对公钥指纹后固定到客户端;不得直接信任网络下载或发现接口取得的密钥。轮换时按受控流程更新信任配置。私钥绝不能交付给客户端。\n\n")
fmt.Fprintf(&b, "当前签名 key_id:`%s`。所有非撤销密钥均可用于验证有效期内已签发的证书和租约。\n\n", a.keyring.Current)
for _, key := range a.keyring.Keys {
if key.Revoked {
continue
}
block, _ := pem.Decode([]byte(key.PublicKeyPEM))
if block == nil {
return "", fmt.Errorf("invalid public key")
}
digest := sha256.Sum256(block.Bytes)
fmt.Fprintf(&b, "### key_id: %s\n\nSPKI SHA-256:`%s`\n\n```pem\n%s\n```\n\n", key.KeyID, hex.EncodeToString(digest[:]), strings.TrimSpace(key.PublicKeyPEM))
}
return b.String(), nil
}
func (a *BusinessAPI) downloadIntegrationKit(c *gin.Context) { func (a *BusinessAPI) downloadIntegrationKit(c *gin.Context) {
language, mode, ok := integrationKitInput(c) language, mode, ok := integrationKitInput(c)
if !ok { if !ok {
return return
} }
kit := buildIntegrationKit(language, mode) kit := buildIntegrationKit(language, mode)
keys, err := a.deploymentVerificationKeys()
if err != nil {
apiError(c, 503, "keyring_unavailable", "当前部署未配置可交付的验签公钥")
return
}
var b strings.Builder var b strings.Builder
fmt.Fprintf(&b, "# 授权平台客户端接入包\n\n协议版本:%s\n\n默认授权平台根地址:%s\n\n", kit.ProtocolVersion, kit.PlatformBaseURL) fmt.Fprintf(&b, "# 授权平台客户端接入包\n\n协议版本:%s\n\n默认授权平台根地址:%s\n\n", kit.ProtocolVersion, kit.PlatformBaseURL)
fmt.Fprintf(&b, "目标:%s,%s\n\n## 工程提示词\n\n%s\n\n## 接口\n\n", kit.LanguageLabel, kit.ModeLabel, kit.Prompt) fmt.Fprintf(&b, "目标:%s,%s\n\n%s## 工程提示词\n\n%s\n\n## 接口\n\n", kit.LanguageLabel, kit.ModeLabel, keys, kit.Prompt)
for _, endpoint := range kit.Endpoints { for _, endpoint := range kit.Endpoints {
fmt.Fprintf(&b, "- `%s %s`:%s\n", endpoint.Method, endpoint.Path, endpoint.Purpose) fmt.Fprintf(&b, "- `%s %s`:%s\n", endpoint.Method, endpoint.Path, endpoint.Purpose)
} }

View File

@@ -57,10 +57,19 @@ func TestIntegrationInputs(t *testing.T) {
} }
} }
func TestIntegrationArchiveAndSignatures(t *testing.T) { func TestIntegrationArchiveAndSignatures(t *testing.T) {
const public = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESr8/VFFwt70o7fwa8HiRNyxWtZEu\nUqzCBfYRG72DazEgeOaSVAdlTv49OujtggXSJzFLOluMENJzaRmp9+iJ0Q==\n-----END PUBLIC KEY-----\n"
a := &BusinessAPI{keyring: &Keyring{Current: "prod-test", Keys: []VerificationKey{{KeyID: "prod-test", PublicKeyPEM: public}, {KeyID: "retired", PublicKeyPEM: public, Revoked: true}}}}
md := httptest.NewRecorder()
mc, _ := gin.CreateTestContext(md)
mc.Request = httptest.NewRequest("GET", "/?language=java&mode=container", nil)
a.downloadIntegrationKit(mc)
if md.Code != 200 || !strings.Contains(md.Body.String(), public) || !strings.Contains(md.Body.String(), "22056bfacc8fe8a240dd2125b629e60ba9f4a5ea0041a1efe034f376a258d562") || strings.Contains(md.Body.String(), "retired") || md.Header().Get("Cache-Control") != "no-store" {
t.Fatal("markdown lacks trusted deployment key")
}
w := httptest.NewRecorder() w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w) c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/?language=java&mode=container", nil) c.Request = httptest.NewRequest("GET", "/?language=java&mode=container", nil)
(&BusinessAPI{}).downloadIntegrationArchive(c) a.downloadIntegrationArchive(c)
if w.Code != 200 || w.Header().Get("Content-Type") != "application/zip" { if w.Code != 200 || w.Header().Get("Content-Type") != "application/zip" {
t.Fatalf("%d %s", w.Code, w.Body) t.Fatalf("%d %s", w.Code, w.Body)
} }
@@ -68,7 +77,7 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if len(archive.File) != 6 { if len(archive.File) != 7 {
t.Fatal("missing files") t.Fatal("missing files")
} }
for _, file := range archive.File { for _, file := range archive.File {
@@ -84,6 +93,9 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
if file.Name == "openapi.json" && !strings.Contains(string(content), defaultIntegrationBaseURL) { if file.Name == "openapi.json" && !strings.Contains(string(content), defaultIntegrationBaseURL) {
t.Fatal("OpenAPI does not use the default platform address") t.Fatal("OpenAPI does not use the default platform address")
} }
if file.Name == "verification-keys.md" && (!strings.Contains(string(content), public) || strings.Contains(string(content), "retired")) {
t.Fatal("incorrect deployment key in archive")
}
if file.Name == "upgrade.md" && !strings.Contains(string(content), "自动升级所需服务端契约") { if file.Name == "upgrade.md" && !strings.Contains(string(content), "自动升级所需服务端契约") {
t.Fatal("missing upgrade plan") t.Fatal("missing upgrade plan")
} }

View File

@@ -0,0 +1,86 @@
package httpapi
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
type deleteDB struct {
*dashboardDB
commands []string
failAudit bool
}
func (d *deleteDB) Connect(context.Context) (driver.Conn, error) { return d, nil }
func (d *deleteDB) ExecContext(_ context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
d.commands = append(d.commands, query)
if strings.Contains(query, "INSERT INTO audit_events") {
if len(args) != 3 {
d.t.Fatal("audit arguments missing")
}
var details map[string]any
if err := json.Unmarshal(args[2].Value.([]byte), &details); err != nil || details["removed_instances"] != float64(1) || details["detached_orders"] != float64(1) {
d.t.Fatal("missing deletion audit context", err, details)
}
if d.failAudit {
return nil, errors.New("audit unavailable")
}
}
return driver.RowsAffected(1), nil
}
func TestDeleteLicense(t *testing.T) {
for _, tc := range []struct {
name string
activated int64
failAudit bool
want int
}{
{"provisioned with order and operations", 0, false, 204},
{"activated", 1, false, 409},
{"audit failure", 0, true, 500},
} {
t.Run(tc.name, func(t *testing.T) {
const activationQuery = `SELECT COUNT(*) FROM license_instances i WHERE i.license_id=? AND (i.status='activated' OR i.activated_at IS NOT NULL OR i.certificate_payload IS NOT NULL OR i.certificate_signature IS NOT NULL OR EXISTS (SELECT 1 FROM activation_operations o WHERE o.instance_id=i.id))`
queries := []dashboardQuery{
{sql: "SELECT status,license_key FROM licenses WHERE id=? FOR UPDATE", args: []any{int64(2)}, rows: [][]driver.Value{{"revoked", "test-key"}}},
{sql: activationQuery, args: []any{int64(2)}, rows: [][]driver.Value{{tc.activated}}},
}
if tc.activated == 0 {
queries = append(queries,
dashboardQuery{sql: "SELECT COUNT(*) FROM license_instances WHERE license_id=?", args: []any{int64(2)}, rows: [][]driver.Value{{int64(1)}}},
dashboardQuery{sql: "SELECT COUNT(*) FROM offline_orders WHERE issued_license_id=?", args: []any{int64(2)}, rows: [][]driver.Value{{int64(1)}}},
dashboardQuery{sql: "SELECT COUNT(*) FROM license_operations WHERE license_id=?", args: []any{int64(2)}, rows: [][]driver.Value{{int64(2)}}},
)
}
stub := &deleteDB{dashboardDB: &dashboardDB{t: t, queries: queries}, failAudit: tc.failAudit}
db := sql.OpenDB(stub)
defer db.Close()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("DELETE", "/licenses/2", nil)
c.Params = gin.Params{{Key: "id", Value: "2"}}
c.Set("admin_id", uint64(1))
(&BusinessAPI{db: db}).deleteLicense(c)
c.Writer.WriteHeaderNow()
if w.Code != tc.want || len(stub.queries) != 0 || stub.committed != (tc.want == 204) {
t.Fatalf("response=%d body=%s remaining=%d committed=%v", w.Code, w.Body.String(), len(stub.queries), stub.committed)
}
if tc.want == 204 {
if len(stub.commands) != 8 || !strings.Contains(stub.commands[0], "audit_events") || !strings.Contains(stub.commands[1], "UPDATE offline_orders") || !strings.Contains(stub.commands[7], "DELETE FROM licenses") {
t.Fatalf("unexpected deletion order: %v", stub.commands)
}
} else if len(stub.commands) > 1 {
t.Fatalf("unexpected cleanup on failure: %v", stub.commands)
}
})
}
}

View File

@@ -173,6 +173,76 @@ func (a *BusinessAPI) issueLicense(c *gin.Context) {
c.JSON(201, gin.H{"data": rec, "idempotent_replay": false}) c.JSON(201, gin.H{"data": rec, "idempotent_replay": false})
} }
func (a *BusinessAPI) deleteLicense(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 {
apiError(c, 400, "invalid_request", "授权 ID 无效")
return
}
adminID := c.MustGet("admin_id")
tx, err := a.db.BeginTx(c, nil)
if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
defer tx.Rollback()
var status, licenseKey string
if err = tx.QueryRowContext(c, "SELECT status,license_key FROM licenses WHERE id=? FOR UPDATE", id).Scan(&status, &licenseKey); errors.Is(err, sql.ErrNoRows) {
apiError(c, 404, "not_found", "授权不存在")
return
} else if err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
var activated int
if err = tx.QueryRowContext(c, `SELECT COUNT(*) FROM license_instances i WHERE i.license_id=? AND (i.status='activated' OR i.activated_at IS NOT NULL OR i.certificate_payload IS NOT NULL OR i.certificate_signature IS NOT NULL OR EXISTS (SELECT 1 FROM activation_operations o WHERE o.instance_id=i.id))`, id).Scan(&activated); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
if activated > 0 {
apiError(c, 409, "license_activated", "该授权已激活,不能删除,请使用撤销")
return
}
var instances, orders, operations int
for _, check := range []struct {
query string
count *int
}{
{"SELECT COUNT(*) FROM license_instances WHERE license_id=?", &instances},
{"SELECT COUNT(*) FROM offline_orders WHERE issued_license_id=?", &orders},
{"SELECT COUNT(*) FROM license_operations WHERE license_id=?", &operations},
} {
if err = tx.QueryRowContext(c, check.query, id).Scan(check.count); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
}
details, _ := json.Marshal(map[string]any{"license_id": id, "license_key": licenseKey, "status": status, "removed_instances": instances, "detached_orders": orders, "removed_operations": operations})
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'license.deleted','license',?,?)", adminID, id, details); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
for _, query := range []string{
"UPDATE offline_orders SET issued_license_id=NULL WHERE issued_license_id=?",
"DELETE FROM activation_operations WHERE instance_id IN (SELECT id FROM license_instances WHERE license_id=?)",
"DELETE FROM heartbeat_operations WHERE instance_id IN (SELECT id FROM license_instances WHERE license_id=?)",
"DELETE FROM instance_state_operations WHERE instance_id IN (SELECT id FROM license_instances WHERE license_id=?)",
"DELETE FROM license_instances WHERE license_id=?",
"DELETE FROM license_operations WHERE license_id=?",
"DELETE FROM licenses WHERE id=?",
} {
if _, err = tx.ExecContext(c, query, id); err != nil {
apiError(c, 500, "internal_error", "删除授权失败")
return
}
}
if err = tx.Commit(); err != nil {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.Status(204)
}
func (a *BusinessAPI) getLicense(c *gin.Context) { func (a *BusinessAPI) getLicense(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64) id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil || id == 0 { if err != nil || id == 0 {

View File

@@ -9,8 +9,8 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权
以下 GET 路由使用现有管理员会话保护,不属于外部客户端运行 API: 以下 GET 路由使用现有管理员会话保护,不属于外部客户端运行 API:
- `/api/v1/integration-kit?language=python&mode=service`:JSON 资料。 - `/api/v1/integration-kit?language=python&mode=service`:JSON 资料。
- `/api/v1/integration-kit/download?language=python&mode=service`:UTF-8 Markdown,包含选定提示词、协议和字段示例。 - `/api/v1/integration-kit/download?language=python&mode=service`:UTF-8 Markdown,包含选定提示词、协议、字段示例和当前部署验签公钥(key ID、SPKI SHA-256 指纹及 PEM)。
- `/api/v1/integration-kit/archive?language=python&mode=service`:ZIP,包含 README.md、protocol.md、openapi.json、prompt.md、test-vectors.json。 - `/api/v1/integration-kit/archive?language=python&mode=service`:ZIP,包含 README.md、protocol.md、upgrade.md、openapi.json、prompt.md、verification-keys.md、test-vectors.json。公钥必须经可信渠道核对后预置,不能把服务端发现结果自动变成信任根。
省略参数默认 python/service。未知语言或模式返回 400,不接受文件路径参数。下载使用 no-store,文件名按受控语言/模式生成。无需新数据库表,不包含任何真实实例 secret、数据库凭据或生产私钥。 省略参数默认 python/service。未知语言或模式返回 400,不接受文件路径参数。下载使用 no-store,文件名按受控语言/模式生成。无需新数据库表,不包含任何真实实例 secret、数据库凭据或生产私钥。
@@ -43,7 +43,7 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权
客户端需按 protocol.md 的“授权文件导入”实现导入入口。接入中心生成的工程提示已包含这一要求,但目前不提供各语言已实现的导入 SDK。客户端应限制文件大小、校验字段及版本、核对受控授权中心允许列表并让用户确认,随后安全保存凭据、在线激活、验签证书和心跳租约。导入不能清空既有时间高水位或静默切换实例。文件本身未签名,不包含可信公钥,不构成离线运行凭证。 客户端需按 protocol.md 的“授权文件导入”实现导入入口。接入中心生成的工程提示已包含这一要求,但目前不提供各语言已实现的导入 SDK。客户端应限制文件大小、校验字段及版本、核对受控授权中心允许列表并让用户确认,随后安全保存凭据、在线激活、验签证书和心跳租约。导入不能清空既有时间高水位或静默切换实例。文件本身未签名,不包含可信公钥,不构成离线运行凭证。
升级方案随 JSON、Markdown 和 ZIP 导出,ZIP 新增 upgrade.md(共六个文件)。实例创建响应设置 Cache-Control: no-store;前端不将 secret 写入日志或浏览器持久化存储。 升级方案随 JSON、Markdown 和 ZIP 导出,ZIP 包含 upgrade.md 与 verification-keys.md(共七个文件)。实例创建响应设置 Cache-Control: no-store;前端不将 secret 写入日志或浏览器持久化存储。
## 开发到生产快速交付 ## 开发到生产快速交付

View File

@@ -26,6 +26,7 @@ export type LicenseInstance = { online_state?:'online'|'offline'|'never_seen'|'u
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 deleteLicense(id:number) { return api.delete(`/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}}) }

View File

@@ -14,7 +14,7 @@ const siteSettings = ref<SiteSettings|null>(null)
async function loadSiteSettings() { try { siteSettings.value = (await getSettings()).data.data } catch { siteSettings.value = null } } async function loadSiteSettings() { try { siteSettings.value = (await getSettings()).data.data } catch { siteSettings.value = null } }
import { getLicense } from '../api' import { getLicense } from '../api'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { createCustomer, createProduct, deleteCustomer, deleteProduct, issueLicense, listCustomers, listLicenses, listProducts, login, logout, me, renewLicense, revokeLicense, type Customer, type License, type Product } from '../api' import { createCustomer, createProduct, deleteCustomer, deleteLicense, deleteProduct, issueLicense, listCustomers, listLicenses, listProducts, login, logout, me, renewLicense, revokeLicense, type Customer, type License, type Product } from '../api'
import { checkApiHealth, type Connection } from '../api-health' import { checkApiHealth, type Connection } from '../api-health'
import OrdersPanel from './OrdersPanel.vue' import OrdersPanel from './OrdersPanel.vue'
import ReleasesPanel from './ReleasesPanel.vue' import ReleasesPanel from './ReleasesPanel.vue'
@@ -75,6 +75,10 @@ async function issue() {
} }
async function removeCustomer(id:number) { await ElMessageBox.confirm('确认删除该客户?','删除确认'); await deleteCustomer(id); await refresh() } async function removeCustomer(id:number) { await ElMessageBox.confirm('确认删除该客户?','删除确认'); await deleteCustomer(id); await refresh() }
async function removeProduct(id:number) { await ElMessageBox.confirm('确认删除该产品?','删除确认'); await deleteProduct(id); await refresh() } async function removeProduct(id:number) { await ElMessageBox.confirm('确认删除该产品?','删除确认'); await deleteProduct(id); await refresh() }
async function removeLicense(id:number) {
try { await ElMessageBox.confirm('仅未激活的授权可删除。删除将清理预置实例和操作记录、解除关联订单的授权引用,并保留审计摘要;此操作不可恢复。确认继续?', '删除授权确认', { type: 'warning', confirmButtonText: '永久删除', cancelButtonText: '取消' }) } catch { return }
try { await deleteLicense(id); ElMessage.success('授权已删除'); await refresh() } catch (e) { ElMessage.error(e instanceof Error ? e.message : '删除失败') }
}
async function revoke(id:number) { async function revoke(id:number) {
await ElMessageBox.confirm('撤销后仅保留后台记录,确认继续?','撤销确认') await ElMessageBox.confirm('撤销后仅保留后台记录,确认继续?','撤销确认')
const operation = `revoke:${id}`, body = '{}', previous = pendingLicenseOps.get(operation) const operation = `revoke:${id}`, body = '{}', previous = pendingLicenseOps.get(operation)
@@ -119,7 +123,7 @@ onMounted(() => { checkConnection(); checkSession() })
<main class="content" v-else><p v-if="siteSettings?.announcement" class="site-announcement" role="note">{{siteSettings.announcement}}</p><p v-if="siteSettings?.support_email" class="subheading">支持联系:<a :href="`mailto:${siteSettings.support_email}`">{{siteSettings.support_email}}</a></p><DashboardPanel v-if="pageView==='dashboard'" @issue="openIssue" @detail="showDetail"/><div v-else class="heading"><div><p class="eyebrow">内部管理台</p><h1>{{title}}</h1><p class="subheading">{{pageView==='admins'?'管理后台账户、启停状态和密码':pageView==='audit'?'查看管理员操作记录':pageView==='settings'?'管理站点展示信息及管理员密码':'客户、订单、授权及实例状态'}}</p></div><el-button v-if="pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" :loading="loading" @click="refresh">刷新</el-button></div><p v-if="error&&pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" class="error">{{ error }}</p> <main class="content" v-else><p v-if="siteSettings?.announcement" class="site-announcement" role="note">{{siteSettings.announcement}}</p><p v-if="siteSettings?.support_email" class="subheading">支持联系:<a :href="`mailto:${siteSettings.support_email}`">{{siteSettings.support_email}}</a></p><DashboardPanel v-if="pageView==='dashboard'" @issue="openIssue" @detail="showDetail"/><div v-else class="heading"><div><p class="eyebrow">内部管理台</p><h1>{{title}}</h1><p class="subheading">{{pageView==='admins'?'管理后台账户、启停状态和密码':pageView==='audit'?'查看管理员操作记录':pageView==='settings'?'管理站点展示信息及管理员密码':'客户、订单、授权及实例状态'}}</p></div><el-button v-if="pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" :loading="loading" @click="refresh">刷新</el-button></div><p v-if="error&&pageView!=='admins'&&pageView!=='audit'&&pageView!=='settings'" class="error">{{ error }}</p>
<section v-if="pageView==='customers'" class="data-section"><div class="section-heading"><div><h2>客户档案</h2><p>共 {{ customerTotal }} 条</p></div><div class="inline-form"><el-input v-model="newCustomer.name" placeholder="客户名称"/><el-input v-model="newCustomer.contact_email" placeholder="联系邮箱"/><el-button type="primary" @click="addCustomer">新增客户</el-button></div></div><el-input v-model="query" placeholder="搜索客户" clearable @change="refresh"/><div class="business-table"><el-table :data="customers" v-loading="loading" empty-text="暂无客户"><el-table-column prop="name" label="名称"/><el-table-column prop="contact_email" label="邮箱"/><el-table-column prop="status" label="状态"/><el-table-column label="操作" width="90"><template #default="scope"><el-button link type="danger" @click="removeCustomer(scope.row.id)">删除</el-button></template></el-table-column></el-table></div></section> <section v-if="pageView==='customers'" class="data-section"><div class="section-heading"><div><h2>客户档案</h2><p>共 {{ customerTotal }} 条</p></div><div class="inline-form"><el-input v-model="newCustomer.name" placeholder="客户名称"/><el-input v-model="newCustomer.contact_email" placeholder="联系邮箱"/><el-button type="primary" @click="addCustomer">新增客户</el-button></div></div><el-input v-model="query" placeholder="搜索客户" clearable @change="refresh"/><div class="business-table"><el-table :data="customers" v-loading="loading" empty-text="暂无客户"><el-table-column prop="name" label="名称"/><el-table-column prop="contact_email" label="邮箱"/><el-table-column prop="status" label="状态"/><el-table-column label="操作" width="90"><template #default="scope"><el-button link type="danger" @click="removeCustomer(scope.row.id)">删除</el-button></template></el-table-column></el-table></div></section>
<section v-if="pageView==='products'" class="data-section"><div class="section-heading"><div><h2>产品目录</h2><p>可用于后续授权规则接入</p></div><div class="inline-form"><el-input v-model="newProduct.code" placeholder="产品编码"/><el-input v-model="newProduct.name" placeholder="产品名称"/><el-button type="primary" @click="addProduct">新增产品</el-button></div></div><div class="business-table"><el-table :data="products" v-loading="loading" empty-text="暂无产品"><el-table-column prop="code" label="编码" width="150"/><el-table-column prop="name" label="名称"/><el-table-column prop="description" label="说明"/><el-table-column label="操作" width="90"><template #default="scope"><el-button link type="danger" @click="removeProduct(scope.row.id)">删除</el-button></template></el-table-column></el-table></div></section> <section v-if="pageView==='products'" class="data-section"><div class="section-heading"><div><h2>产品目录</h2><p>可用于后续授权规则接入</p></div><div class="inline-form"><el-input v-model="newProduct.code" placeholder="产品编码"/><el-input v-model="newProduct.name" placeholder="产品名称"/><el-button type="primary" @click="addProduct">新增产品</el-button></div></div><div class="business-table"><el-table :data="products" v-loading="loading" empty-text="暂无产品"><el-table-column prop="code" label="编码" width="150"/><el-table-column prop="name" label="名称"/><el-table-column prop="description" label="说明"/><el-table-column label="操作" width="90"><template #default="scope"><el-button link type="danger" @click="removeProduct(scope.row.id)">删除</el-button></template></el-table-column></el-table></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> <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><el-button link type="danger" @click="removeLicense(scope.row.id)">删除</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!)"/><TrustDeliveryPanel v-for="instance in instances" :key="instance.instance_id" :instance="instance"/><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> <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!)"/><TrustDeliveryPanel v-for="instance in instances" :key="instance.instance_id" :instance="instance"/><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>