diff --git a/backend/internal/httpapi/business.go b/backend/internal/httpapi/business.go index b49c5f5..0e7b027 100644 --- a/backend/internal/httpapi/business.go +++ b/backend/internal/httpapi/business.go @@ -94,6 +94,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) { secured.GET("/licenses/:id/instances", a.listInstances) secured.POST("/licenses/:id/instances", a.provisionInstance) secured.GET("/licenses/:id/instance-credentials", a.instanceCredentials) + secured.DELETE("/licenses/:id", a.deleteLicense) secured.POST("/products/:id/releases", a.createRelease) secured.GET("/products/:id/releases", a.listReleases) api.POST("/customers/:customer_id/releases/:id/download", a.downloadRelease) diff --git a/backend/internal/httpapi/integration_archive.go b/backend/internal/httpapi/integration_archive.go index df921de..177385a 100644 --- a/backend/internal/httpapi/integration_archive.go +++ b/backend/internal/httpapi/integration_archive.go @@ -71,10 +71,16 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) { return } kit := buildIntegrationKit(language, mode) + keys, err := a.deploymentVerificationKeys() + if err != nil { + apiError(c, 503, "keyring_unavailable", "当前部署未配置可交付的验签公钥") + return + } files := map[string][]byte{ - "README.md": []byte("# 客户端接入包\n\n阅读 protocol.md、upgrade.md 与 openapi.json,将 prompt.md 提供给实现工程师。upgrade.md 说明当前可用下载能力和自动升级待建设的契约;当前没有客户端版本检查或签名升级清单。test-vectors.json 使用随机测试密钥,绝不能导入生产。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"), - "prompt.md": []byte(kit.Prompt), - "test-vectors.json": vectors, + "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), + "test-vectors.json": vectors, } for _, name := range []string{"protocol.md", "upgrade.md", "openapi.json"} { content, err := integrationAsset(name) @@ -86,7 +92,7 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) { } var buffer bytes.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) if err == nil { _, err = file.Write(files[name]) diff --git a/backend/internal/httpapi/integration_kit.go b/backend/internal/httpapi/integration_kit.go index dfab338..958281a 100644 --- a/backend/internal/httpapi/integration_kit.go +++ b/backend/internal/httpapi/integration_kit.go @@ -1,7 +1,10 @@ package httpapi import ( + "crypto/sha256" "embed" + "encoding/hex" + "encoding/pem" "fmt" "net/http" "strings" @@ -135,15 +138,41 @@ func (a *BusinessAPI) integrationKit(c *gin.Context) { 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) { language, mode, ok := integrationKitInput(c) if !ok { return } kit := buildIntegrationKit(language, mode) + keys, err := a.deploymentVerificationKeys() + if err != nil { + apiError(c, 503, "keyring_unavailable", "当前部署未配置可交付的验签公钥") + return + } var b strings.Builder 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 { fmt.Fprintf(&b, "- `%s %s`:%s\n", endpoint.Method, endpoint.Path, endpoint.Purpose) } diff --git a/backend/internal/httpapi/integration_kit_test.go b/backend/internal/httpapi/integration_kit_test.go index 996f5ff..8ee77f4 100644 --- a/backend/internal/httpapi/integration_kit_test.go +++ b/backend/internal/httpapi/integration_kit_test.go @@ -57,10 +57,19 @@ func TestIntegrationInputs(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() c, _ := gin.CreateTestContext(w) 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" { t.Fatalf("%d %s", w.Code, w.Body) } @@ -68,7 +77,7 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) { if err != nil { t.Fatal(err) } - if len(archive.File) != 6 { + if len(archive.File) != 7 { t.Fatal("missing files") } for _, file := range archive.File { @@ -84,6 +93,9 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) { if file.Name == "openapi.json" && !strings.Contains(string(content), defaultIntegrationBaseURL) { 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), "自动升级所需服务端契约") { t.Fatal("missing upgrade plan") } diff --git a/backend/internal/httpapi/license_delete_test.go b/backend/internal/httpapi/license_delete_test.go new file mode 100644 index 0000000..57cb44a --- /dev/null +++ b/backend/internal/httpapi/license_delete_test.go @@ -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) + } + }) + } +} diff --git a/backend/internal/httpapi/licenses.go b/backend/internal/httpapi/licenses.go index 15a17f1..dfa737b 100644 --- a/backend/internal/httpapi/licenses.go +++ b/backend/internal/httpapi/licenses.go @@ -173,6 +173,76 @@ func (a *BusinessAPI) issueLicense(c *gin.Context) { 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) { id, err := strconv.ParseUint(c.Param("id"), 10, 64) if err != nil || id == 0 { diff --git a/docs/client-integration-center.md b/docs/client-integration-center.md index ef577e5..3fb46df 100644 --- a/docs/client-integration-center.md +++ b/docs/client-integration-center.md @@ -9,8 +9,8 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权 以下 GET 路由使用现有管理员会话保护,不属于外部客户端运行 API: - `/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/archive?language=python&mode=service`:ZIP,包含 README.md、protocol.md、openapi.json、prompt.md、test-vectors.json。 +- `/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、upgrade.md、openapi.json、prompt.md、verification-keys.md、test-vectors.json。公钥必须经可信渠道核对后预置,不能把服务端发现结果自动变成信任根。 省略参数默认 python/service。未知语言或模式返回 400,不接受文件路径参数。下载使用 no-store,文件名按受控语言/模式生成。无需新数据库表,不包含任何真实实例 secret、数据库凭据或生产私钥。 @@ -43,7 +43,7 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权 客户端需按 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 写入日志或浏览器持久化存储。 ## 开发到生产快速交付 diff --git a/frontend/src/api.ts b/frontend/src/api.ts index f5434e1..b6e7604 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -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 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 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 renewLicense(id:number,expires_at:string,idempotencyKey:string) { return api.post(`/licenses/${id}/renew`,{expires_at},{headers:{'Idempotency-Key':idempotencyKey}}) } diff --git a/frontend/src/views/Overview.vue b/frontend/src/views/Overview.vue index 726f6a5..4d6f427 100644 --- a/frontend/src/views/Overview.vue +++ b/frontend/src/views/Overview.vue @@ -14,7 +14,7 @@ const siteSettings = ref(null) async function loadSiteSettings() { try { siteSettings.value = (await getSettings()).data.data } catch { siteSettings.value = null } } import { getLicense } from '../api' 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 OrdersPanel from './OrdersPanel.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 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) { await ElMessageBox.confirm('撤销后仅保留后台记录,确认继续?','撤销确认') const operation = `revoke:${id}`, body = '{}', previous = pendingLicenseOps.get(operation) @@ -119,7 +123,7 @@ onMounted(() => { checkConnection(); checkSession() })

{{siteSettings.announcement}}

支持联系:{{siteSettings.support_email}}

内部管理台

{{title}}

{{pageView==='admins'?'管理后台账户、启停状态和密码':pageView==='audit'?'查看管理员操作记录':pageView==='settings'?'管理站点展示信息及管理员密码':'客户、订单、授权及实例状态'}}

刷新

{{ error }}

客户档案

共 {{ customerTotal }} 条

新增客户

产品目录

可用于后续授权规则接入

新增产品
-

期限授权

共 {{ licenseTotal }} 条,签发后通过“实例”创建并交付客户端激活凭据

签发授权
+

期限授权

共 {{ licenseTotal }} 条,签发后通过“实例”创建并交付客户端激活凭据

签发授权
License 密钥
{{detail.license_key}}
客户
{{detail.customer_name}}
产品
{{detail.product_name}}
类型
期限授权
开始时间
{{formatDateTime(detail.starts_at)}}
到期时间
{{formatDateTime(detail.expires_at)}}
状态
{{detail.status}}
查看实例 / 冻结管理
刷新状态

在线表示服务端最近 3 分钟收到心跳;超时显示离线,从未心跳显示从未上报。离线不代表授权失效;状态在刷新时更新。

{{ instanceError }}