feat: localize license states and restore revoked licenses
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 16:11:09 +08:00
parent f4b99e50cd
commit 09910db251
8 changed files with 141 additions and 6 deletions

View File

@@ -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") })
}

View File

@@ -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)
}
}

View File

@@ -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)
}
})
}
}

View File

@@ -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 {
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})

View File

@@ -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` 审计在同一事务内完成。
恢复沿用原开始时间、到期时间、实例绑定和凭据,不延长有效期;已过期授权恢复后显示“已到期”,需再续期。撤销及恢复作用于该授权下所有实例,客户端在下一次成功心跳时取得新状态。已冻结实例需单独解除冻结,客户或产品停用仍会限制使用。实例“已传播状态”保留客户端上次心跳结果,可与当前授权状态暂时不同。

View File

@@ -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}}) }

View File

@@ -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:'<div v-if="label===\'状态\'||label===\'操作\'"><slot :row="row" /></div>'})
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')

File diff suppressed because one or more lines are too long