From 09910db251b52e3232f8cdc588b000fbc78fa6ac Mon Sep 17 00:00:00 2001 From: xiewenjun <88080888@163.com> Date: Mon, 12 Oct 2026 16:11:09 +0800 Subject: [PATCH] feat: localize license states and restore revoked licenses Co-Authored-By: Craft Agent --- backend/internal/httpapi/business.go | 1 + .../httpapi/heartbeat_integration_test.go | 9 +++ .../internal/httpapi/license_restore_test.go | 72 +++++++++++++++++++ backend/internal/httpapi/licenses.go | 13 +++- docs/admin-modules.md | 6 ++ frontend/src/api.ts | 1 + frontend/src/views/Overview.test.ts | 26 ++++++- frontend/src/views/Overview.vue | 19 +++-- 8 files changed, 141 insertions(+), 6 deletions(-) create mode 100644 backend/internal/httpapi/license_restore_test.go diff --git a/backend/internal/httpapi/business.go b/backend/internal/httpapi/business.go index 0e7b027..a9878cd 100644 --- a/backend/internal/httpapi/business.go +++ b/backend/internal/httpapi/business.go @@ -101,6 +101,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) { secured.POST("/instances/:instance_id/freeze", a.freezeInstance) secured.POST("/licenses", a.issueLicense) secured.POST("/licenses/:id/revoke", func(c *gin.Context) { a.operateLicense(c, "revoke") }) + secured.POST("/licenses/:id/restore", func(c *gin.Context) { a.operateLicense(c, "restore") }) secured.POST("/licenses/:id/renew", func(c *gin.Context) { a.operateLicense(c, "renew") }) } diff --git a/backend/internal/httpapi/heartbeat_integration_test.go b/backend/internal/httpapi/heartbeat_integration_test.go index 67781f4..0fc6e35 100644 --- a/backend/internal/httpapi/heartbeat_integration_test.go +++ b/backend/internal/httpapi/heartbeat_integration_test.go @@ -137,4 +137,13 @@ func testHeartbeatMySQL(t *testing.T, db *sql.DB, r *gin.Engine, cookie *http.Co if response.Data.Payload.State != "revoked" { t.Fatal("revocation not propagated") } + restorePath := "/api/v1/licenses/" + strconv.FormatUint(licenseID, 10) + "/restore" + if w = request(restorePath, `{}`, "heartbeat-restore", true); w.Code != 200 { + t.Fatalf("restore=%d body=%s", w.Code, w.Body) + } + w = request(path, body, "restored", false) + json.Unmarshal(w.Body.Bytes(), &response) + if w.Code != 200 || response.Data.Payload.State != "active" { + t.Fatalf("restoration not propagated: %d %s", w.Code, w.Body) + } } diff --git a/backend/internal/httpapi/license_restore_test.go b/backend/internal/httpapi/license_restore_test.go new file mode 100644 index 0000000..8437916 --- /dev/null +++ b/backend/internal/httpapi/license_restore_test.go @@ -0,0 +1,72 @@ +package httpapi + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "github.com/gin-gonic/gin" + "net/http/httptest" + "strings" + "testing" + "time" +) + +type restoreDB struct { + *dashboardDB + commands []string + failAudit bool +} + +func (d *restoreDB) Connect(context.Context) (driver.Conn, error) { return d, nil } +func (d *restoreDB) ExecContext(_ context.Context, q string, args []driver.NamedValue) (driver.Result, error) { + d.commands = append(d.commands, q) + if strings.Contains(q, "INSERT INTO audit_events") && d.failAudit { + return nil, errors.New("audit unavailable") + } + return driver.RowsAffected(1), nil +} +func TestRestoreLicense(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + for _, tc := range []struct { + name, status string + expiry time.Time + fail bool + want int + result string + }{ + {"valid", "revoked", now.Add(time.Hour), false, 200, "active"}, + {"expired", "revoked", now.Add(-time.Hour), false, 200, "expired"}, + {"not revoked", "active", now.Add(time.Hour), false, 409, ""}, + {"audit failure", "revoked", now.Add(time.Hour), true, 500, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + d := &restoreDB{dashboardDB: &dashboardDB{t: t, queries: []dashboardQuery{ + {sql: licenseSelect + " WHERE l.id=? FOR UPDATE", args: []any{int64(2)}, rows: [][]driver.Value{testLicenseRow(2, tc.status, now.Add(-2*time.Hour), tc.expiry, now)}}, + {sql: "SELECT id,license_id,operation,idempotency_key,request_fingerprint FROM license_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", args: []any{int64(1), "restore", "restore-test"}}, + }}, failAudit: tc.fail} + db := sql.OpenDB(d) + defer db.Close() + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("POST", "/api/v1/licenses/2/restore", strings.NewReader("{}")) + c.Request.Header.Set("Idempotency-Key", "restore-test") + c.Params = gin.Params{{Key: "id", Value: "2"}} + c.Set("admin_id", uint64(1)) + (&BusinessAPI{db: db}).operateLicense(c, "restore") + c.Writer.WriteHeaderNow() + if w.Code != tc.want || d.committed != (tc.want == 200) { + t.Fatalf("code=%d committed=%v body=%s", w.Code, d.committed, w.Body) + } + if tc.want == 200 && (!strings.Contains(w.Body.String(), `"status":"`+tc.result+`"`) || !strings.Contains(w.Body.String(), tc.expiry.Format(time.RFC3339))) { + t.Fatalf("validity changed: %s", w.Body) + } + if tc.want == 409 && len(d.commands) != 0 { + t.Fatal("invalid state mutated") + } + if tc.want == 200 && (len(d.commands) != 3 || d.commands[0] != "UPDATE licenses SET status='active',revoked_at=NULL WHERE id=?") { + t.Fatal("unexpected restore writes", d.commands) + } + }) + } +} diff --git a/backend/internal/httpapi/licenses.go b/backend/internal/httpapi/licenses.go index dfa737b..de3eb8a 100644 --- a/backend/internal/httpapi/licenses.go +++ b/backend/internal/httpapi/licenses.go @@ -345,6 +345,15 @@ func (a *BusinessAPI) operateLicense(c *gin.Context, operation string) { apiError(c, 500, "internal_error", "撤销失败") return } + } else if operation == "restore" { + if rec.Status != "revoked" { + apiError(c, 409, "invalid_state", "仅已撤销的授权可以恢复") + return + } + if _, err = tx.ExecContext(c, "UPDATE licenses SET status='active',revoked_at=NULL WHERE id=?", id); err != nil { + apiError(c, 500, "internal_error", "恢复失败") + return + } } else { if rec.Status == "revoked" || !expires.After(rec.ExpiresAt) { apiError(c, 400, "invalid_request", "续期时间必须晚于当前结束时间且授权未撤销") @@ -371,7 +380,9 @@ func (a *BusinessAPI) operateLicense(c *gin.Context, operation string) { if operation == "revoke" { rec.Status = "revoked" } else { - rec.ExpiresAt = expires + if operation == "renew" { + rec.ExpiresAt = expires + } rec.Status = currentLicenseStatus("active", rec.StartsAt, rec.ExpiresAt, time.Now().UTC()) } c.JSON(200, gin.H{"data": rec, "idempotent_replay": false}) diff --git a/docs/admin-modules.md b/docs/admin-modules.md index cbfb00b..36f3804 100644 --- a/docs/admin-modules.md +++ b/docs/admin-modules.md @@ -60,3 +60,9 @@ go run ./cmd/admin-init -username admin -email admin@example.test -password 'YOU Schema 11 后,配置 LICENSE_CREDENTIAL_ENCRYPTION_KEY_FILE(独立 32 字节原始随机密钥,只读挂载、权限 0600)可加密保存新实例 secret。管理员可重复查看及导出 JSON,读取记录 instance.credentials.viewed 审计事件并返回 no-store;凭据只在当前视图,不写浏览器持久存储。旧实例无法恢复,未配置时仍仅首次返回。加密密钥须安全备份,不可随意替换,不提供自动轮换。 激活状态和连接状态分别展示;最近 3 分钟收到心跳为在线,超时为离线,无心跳为从未上报,未来时间为未知。点击刷新更新状态,离线不表示授权失效。 + +## 授权状态与撤销恢复 + +License 授权列表、详情及实例状态以中文展示,API 状态枚举保持不变。已撤销授权的操作栏显示“恢复授权”,调用 `POST /api/v1/licenses/:id/restore`,必须携带 `Idempotency-Key`。仅已撤销授权可恢复,状态更新、操作记录及 `license.restore` 审计在同一事务内完成。 + +恢复沿用原开始时间、到期时间、实例绑定和凭据,不延长有效期;已过期授权恢复后显示“已到期”,需再续期。撤销及恢复作用于该授权下所有实例,客户端在下一次成功心跳时取得新状态。已冻结实例需单独解除冻结,客户或产品停用仍会限制使用。实例“已传播状态”保留客户端上次心跳结果,可与当前授权状态暂时不同。 diff --git a/frontend/src/api.ts b/frontend/src/api.ts index b6e7604..16d064c 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -27,6 +27,7 @@ export async function setInstanceFrozen(instanceID:string,frozen:boolean,key:str 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 restoreLicense(id:number,idempotencyKey:string) { return api.post(`/licenses/${id}/restore`,{}, {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}}) } diff --git a/frontend/src/views/Overview.test.ts b/frontend/src/views/Overview.test.ts index 9d6b4cd..02862eb 100644 --- a/frontend/src/views/Overview.test.ts +++ b/frontend/src/views/Overview.test.ts @@ -1,13 +1,15 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { flushPromises, mount } from '@vue/test-utils' import { defineComponent } from 'vue' +const confirmation = vi.hoisted(() => vi.fn()) +vi.mock('element-plus', () => ({ ElMessage: { success:vi.fn(), error:vi.fn() }, ElMessageBox: { confirm:confirmation } })) const routeState = vi.hoisted(() => ({meta:{view:'licenses'},query:{}})) const routerMock = vi.hoisted(() => ({push:vi.fn(),replace:vi.fn()})) vi.mock('vue-router', () => ({useRoute:()=>routeState,useRouter:()=>routerMock})) const health = vi.hoisted(() => ({ checkApiHealth: vi.fn() })) vi.mock('../api-health', () => health) -const business = vi.hoisted(() => ({ me: vi.fn(), listCustomers: vi.fn(), listProducts: vi.fn(), listLicenses: vi.fn(), issueLicense: vi.fn(), renewLicense: vi.fn(), listLicenseInstances: vi.fn() })) +const business = vi.hoisted(() => ({ me: vi.fn(), listCustomers: vi.fn(), listProducts: vi.fn(), listLicenses: vi.fn(), issueLicense: vi.fn(), renewLicense: vi.fn(), restoreLicense:vi.fn(), listLicenseInstances: vi.fn() })) vi.mock('../api', () => business) const settingsApi = vi.hoisted(() => ({ getSettings: vi.fn() })) vi.mock('../admin-api', () => settingsApi) @@ -25,6 +27,28 @@ const ButtonStub = defineComponent({ }) describe('Overview API status', () => { + it('shows Chinese revoked status and restores with the same key on retry', async () => { + routeState.meta.view = 'licenses' + health.checkApiHealth.mockResolvedValue('online') + business.me.mockResolvedValue({data:{data:{username:'admin'}}}) + business.listCustomers.mockResolvedValue({data:{data:[],meta:{total:0}}}) + business.listProducts.mockResolvedValue({data:{data:[]}}) + const row = {id:7,status:'revoked',expires_at:'2027-01-01T00:00:00Z'} + business.listLicenses.mockResolvedValue({data:{data:[row],meta:{total:1}}}) + confirmation.mockResolvedValue(true) + business.restoreLicense.mockRejectedValueOnce(new Error('网络错误')).mockResolvedValueOnce({}) + const Column = defineComponent({props:['label'],setup:()=>({row}),template:'
'}) + const wrapper = mount(Overview,{global:{stubs:{'router-link':true,'el-button':ButtonStub,'el-table':TableStub,'el-table-column':Column,'el-dialog':true,'el-drawer':true,'el-input':true,'el-form':true,'el-select':true,'el-option':true,'el-date-picker':true,'el-pagination':true},directives:{loading:()=>{}}}}) + await flushPromises() + expect(wrapper.text()).toContain('已撤销') + const restore = wrapper.findAll('button').find(b=>b.text()==='恢复授权')! + await restore.trigger('click'); await flushPromises() + const key=business.restoreLicense.mock.calls[0][1] + await restore.trigger('click'); await flushPromises() + expect(business.restoreLicense).toHaveBeenLastCalledWith(7,key) + expect(confirmation.mock.calls[0][0]).toContain('原有效期') + wrapper.unmount() + }) it('renews using a date picker, validates dates and reuses the key on retry', async () => { routeState.meta.view = 'licenses' health.checkApiHealth.mockResolvedValue('online') diff --git a/frontend/src/views/Overview.vue b/frontend/src/views/Overview.vue index 4d6f427..e478653 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, deleteLicense, 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, restoreLicense, 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' @@ -49,6 +49,17 @@ const issueForm = ref({ customer_id: null as number | null, product_id: null as const issuing = ref(false), licensePage = ref(1) let pendingIssue: { body: string; key: string } | null = null const pendingLicenseOps = new Map() +function statusLabel(status:string) { return ({active:'有效',scheduled:'未开始',pending:'未开始',expired:'已到期',revoked:'已撤销',activated:'已激活',provisioned:'未激活',not_activated:'未激活',frozen:'已冻结',none:'未冻结',unknown:'未知'} as Record)[status] ?? '未知' } +const restoringLicense = ref(null) +async function restore(id:number) { + if (restoringLicense.value !== null) return + try { await ElMessageBox.confirm('恢复后沿用原有效期和实例绑定。已过期授权仍需续期,冻结实例仍需解除冻结;客户端将在下一次心跳时获取恢复后的状态。确认恢复?', '恢复授权确认', { confirmButtonText:'恢复授权', cancelButtonText:'取消' }) } catch { return } + const operation = `restore:${id}`, body = '{}', previous = pendingLicenseOps.get(operation) + const retry = previous ?? { body, key:crypto.randomUUID() } + pendingLicenseOps.set(operation, retry) + restoringLicense.value = id + try { await restoreLicense(id, retry.key); pendingLicenseOps.delete(operation); ElMessage.success('授权已恢复'); await refresh(); if (selectedLicenseID.value === id) await showInstances(id) } catch (e) { ElMessage.error(e instanceof Error ? e.message : '恢复失败') } finally { restoringLicense.value = null } +} const newCustomer = ref({ name: '', contact_email: '' }), newProduct = ref({ code: '', name: '', description: '' }) async function refresh() { loading.value = true; error.value = ''; try { const [cs, ps, ls] = await Promise.all([listCustomers({ q: query.value, page:customerPage.value }), listProducts(), listLicenses({ page: licensePage.value, q:licenseQuery.value, status:String(route.query.status??licenseStatus.value) })]); customers.value = cs.data.data; customerTotal.value = cs.data.meta.total; products.value = ps.data.data; licenses.value = ls.data.data; licenseTotal.value = ls.data.meta.total } catch (e) { error.value = e instanceof Error ? e.message : '加载失败' } finally { loading.value = false } } async function checkConnection() { connection.value = 'checking'; connection.value = await checkApiHealth() } @@ -80,7 +91,7 @@ async function removeLicense(id:number) { 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('撤销后仅保留后台记录,确认继续?','撤销确认') + try { await ElMessageBox.confirm('撤销将影响该授权下所有实例。后续可恢复授权,客户端在下一次心跳时获取状态;离线旧租约不会立即失效。确认继续?','撤销确认') } catch { return } const operation = `revoke:${id}`, body = '{}', previous = pendingLicenseOps.get(operation) const retry = previous && previous.body === body ? previous : { body, key: crypto.randomUUID() } pendingLicenseOps.set(operation, retry) @@ -123,10 +134,10 @@ 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 }}

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

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

{{ instanceError }}