feat: deliver deployment verification keys and instance trust config
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
@@ -72,6 +72,7 @@ func registerBusinessRoutes(r *gin.Engine, a *BusinessAPI) {
|
||||
secured.GET("/settings", a.getSettings)
|
||||
secured.PUT("/settings", a.updateSettings)
|
||||
secured.POST("/settings/password", a.changePassword)
|
||||
secured.GET("/integration-trust", a.integrationTrust)
|
||||
secured.GET("/integration-kit", a.integrationKit)
|
||||
secured.GET("/integration-kit/download", a.downloadIntegrationKit)
|
||||
secured.GET("/integration-kit/archive", a.downloadIntegrationArchive)
|
||||
|
||||
@@ -91,3 +91,9 @@ SPA 应通过同源 BFF 调用,不得在浏览器长期保存实例 secret。
|
||||
## 交付验收
|
||||
|
||||
覆盖正常验签、篡改字段/签名、未知/撤销密钥、v1/额外字段、实例不匹配、过期和超过 14 天、时钟回拨、非 active、幂等重试、429、掉线与原子存储失败。测试向量只使用随机测试密钥,绝不能导入生产信任配置。
|
||||
|
||||
## 管理员交付的信任配置(yhy-license-trust v1)
|
||||
|
||||
从对应环境管理后台“授权 → 实例”下载信任 JSON,通过受控渠道交付。字段:format=yhy-license-trust、version=1、api_base_url(HTTPS 根地址,本机允许 HTTP 回环)、protocol_versions=[license-v2,lease-v2]、signature_algorithm=ECDSA-P256-SHA256、current_key_id、keys=[{key_id,public_key_pem,revoked,spki_sha256}]、instance_id、customer_id、product_id。spki_sha256 是公钥 SPKI DER 的 SHA-256 小写十六进制摘要。文件只含未撤销公钥,不含 secret;激活凭据文件单独导入。
|
||||
|
||||
客户端实现严格格式/大小校验,验证公钥为 P-256 SPKI PEM、摘要匹配、key_id 不重复且 current_key_id 存在、revoked=false,核对绑定与授权中心地址并提示操作者确认。只有受控交付才可新增信任根,不可通过发现接口自动新增。验证 license-v2、lease-v2 签名与实例/客户/产品绑定、有效期和状态;导入不是激活。开发先通过 ZIP 测试向量,再连接开发中心;生产重新交付生产信任配置和凭据。已交付公钥仍需受控撤销/更新策略,导出文件不能证明未来未撤销。
|
||||
|
||||
@@ -118,7 +118,7 @@ func integrationPrompt(language, mode string) string {
|
||||
|
||||
默认授权平台根地址:%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 持续用于心跳和下载;配置加密留存后可重复查看,旧实例无法从哈希恢复。公钥及绑定信息从对应管理后台实例页导出 yhy-license-trust v1 JSON(详见 protocol.md),客户端实现严格导入并通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,旧实例丢失 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。
|
||||
|
||||
|
||||
32
backend/internal/httpapi/integration_trust.go
Normal file
32
backend/internal/httpapi/integration_trust.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (a *BusinessAPI) integrationTrust(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
if a.keyring == nil {
|
||||
apiError(c, 503, "keyring_unavailable", "当前部署未配置 v2 公钥环,请配置 LICENSE_KEYRING_FILE 及匹配签名私钥")
|
||||
return
|
||||
}
|
||||
keys := make([]gin.H, 0, len(a.keyring.Keys))
|
||||
for _, key := range a.keyring.Keys {
|
||||
block, _ := pem.Decode([]byte(key.PublicKeyPEM))
|
||||
if block == nil {
|
||||
apiError(c, 503, "keyring_unavailable", "公钥格式无效")
|
||||
return
|
||||
}
|
||||
if _, err := x509.ParsePKIXPublicKey(block.Bytes); err != nil {
|
||||
apiError(c, 503, "keyring_unavailable", "公钥格式无效")
|
||||
return
|
||||
}
|
||||
digest := sha256.Sum256(block.Bytes)
|
||||
keys = append(keys, gin.H{"key_id": key.KeyID, "public_key_pem": key.PublicKeyPEM, "revoked": key.Revoked, "spki_sha256": hex.EncodeToString(digest[:])})
|
||||
}
|
||||
c.JSON(200, gin.H{"data": gin.H{"current_key_id": a.keyring.Current, "keys": keys}})
|
||||
}
|
||||
39
backend/internal/httpapi/integration_trust_test.go
Normal file
39
backend/internal/httpapi/integration_trust_test.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIntegrationTrust(t *testing.T) {
|
||||
const public = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESr8/VFFwt70o7fwa8HiRNyxWtZEu\nUqzCBfYRG72DazEgeOaSVAdlTv49OujtggXSJzFLOluMENJzaRmp9+iJ0Q==\n-----END PUBLIC KEY-----\n"
|
||||
for _, configured := range []bool{false, true} {
|
||||
a := &BusinessAPI{}
|
||||
if configured {
|
||||
a.keyring = &Keyring{Current: "prod-test", Keys: []VerificationKey{{KeyID: "prod-test", PublicKeyPEM: public}, {KeyID: "old", PublicKeyPEM: public, Revoked: true}}}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
a.integrationTrust(c)
|
||||
if !configured {
|
||||
if w.Code != 503 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
continue
|
||||
}
|
||||
body := w.Body.String()
|
||||
if w.Code != 200 || !strings.Contains(body, "22056bfacc8fe8a240dd2125b629e60ba9f4a5ea0041a1efe034f376a258d562") || !strings.Contains(body, `"revoked":true`) || strings.Contains(body, "PRIVATE KEY") || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("invalid trust response")
|
||||
}
|
||||
}
|
||||
r := gin.New()
|
||||
RegisterBusiness(r, &sql.DB{})
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/integration-trust", nil))
|
||||
if w.Code != 401 {
|
||||
t.Fatal("unauthenticated trust access")
|
||||
}
|
||||
}
|
||||
@@ -44,3 +44,11 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权
|
||||
客户端需按 protocol.md 的“授权文件导入”实现导入入口。接入中心生成的工程提示已包含这一要求,但目前不提供各语言已实现的导入 SDK。客户端应限制文件大小、校验字段及版本、核对受控授权中心允许列表并让用户确认,随后安全保存凭据、在线激活、验签证书和心跳租约。导入不能清空既有时间高水位或静默切换实例。文件本身未签名,不包含可信公钥,不构成离线运行凭证。
|
||||
|
||||
升级方案随 JSON、Markdown 和 ZIP 导出,ZIP 新增 upgrade.md(共六个文件)。实例创建响应设置 Cache-Control: no-store;前端不将 secret 写入日志或浏览器持久化存储。
|
||||
|
||||
## 开发到生产快速交付
|
||||
|
||||
接入中心展示当前部署公钥环、当前 key_id、撤销标记和 SHA-256(SPKI DER)指纹,支持复制/下载未撤销 PEM。需要管理员会话,公钥接口为 GET /api/v1/integration-trust;未配置 v2 keyring 返回 503。
|
||||
|
||||
授权实例页可导出 yhy-license-trust v1 JSON:api_base_url、protocol_versions、signature_algorithm、current_key_id、未撤销 keys(含 PEM/指纹)、instance_id、customer_id、product_id。不含 secret;激活凭据另行导出。地址必须由管理员确认,HTTPS 根地址或本机 HTTP 回环地址;本机 API 使用 18081,而非前端 15173。
|
||||
|
||||
客户端需实现此新格式的严格导入与受保护存储。导入公钥须经过受控渠道确认,不能把发现接口当作信任根;验证签名、key_id、实例/客户/产品绑定、时间及状态。生产切换必须从生产后台重新交付地址、信任和凭据。导出不是证书,不会激活客户端,也不替代后续撤销策略。各语言 SDK 尚未在本仓库实现。
|
||||
|
||||
@@ -48,3 +48,7 @@ export function validatePassword(current:string, next:string, confirmation:strin
|
||||
if (next !== confirmation) return '两次输入的新密码不一致'
|
||||
return ''
|
||||
}
|
||||
|
||||
export type TrustKey = {key_id:string;public_key_pem:string;revoked:boolean;spki_sha256:string}
|
||||
export type IntegrationTrust = {current_key_id:string;keys:TrustKey[]}
|
||||
export const getIntegrationTrust = () => api.get<{data:IntegrationTrust}>('/integration-trust')
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
const calls = vi.hoisted(() => ({getIntegrationKit:vi.fn()}))
|
||||
const calls = vi.hoisted(() => ({getIntegrationKit:vi.fn(),getIntegrationTrust:vi.fn()}))
|
||||
vi.mock('../admin-api', async importOriginal => ({...await importOriginal<typeof import('../admin-api')>(),...calls}))
|
||||
import IntegrationPanel from './IntegrationPanel.vue'
|
||||
const kit = {protocol_version:'license-v2 / lease-v2',platform_base_url:'https://license.yihuiyong.cn',language:'python',language_label:'Python 3.11+',mode:'service',mode_label:'常驻服务',endpoints:[{method:'POST',path:'/heartbeat',purpose:'刷新租约'}],security_rules:['不得泄露 secret'],prompt:'实现 LicenseClient',protocol:'DER signature',payload_example:{version:'lease-v2'}}
|
||||
beforeEach(() => {vi.resetAllMocks();calls.getIntegrationKit.mockResolvedValue({data:{data:kit}})})
|
||||
beforeEach(() => {vi.resetAllMocks();calls.getIntegrationTrust.mockResolvedValue({data:{data:{current_key_id:"test",keys:[]}}});calls.getIntegrationKit.mockResolvedValue({data:{data:kit}})})
|
||||
describe('IntegrationPanel',()=>{
|
||||
it('loads generated materials and exposes both download formats',async()=>{
|
||||
const wrapper=mount(IntegrationPanel,{global:{plugins:[ElementPlus]}});await flushPromises()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import TrustDeliveryPanel from './TrustDeliveryPanel.vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { getIntegrationKit, type IntegrationKit, type IntegrationLanguage, type IntegrationMode } from '../admin-api'
|
||||
@@ -36,6 +37,15 @@ onMounted(load)
|
||||
<template>
|
||||
<section class="data-section integration-panel">
|
||||
<div class="section-heading"><div><h2>客户端接入包</h2><p>选择目标语言和运行方式,交付给外部工程团队实现客户端 SDK 与升级能力。</p></div><el-button :loading="loading" @click="load">刷新资料</el-button></div>
|
||||
<h3>快速接入:开发联调 → 生产上线</h3>
|
||||
<ol>
|
||||
<li>开发:准备本机签名私钥及匹配的 v2 公钥环,创建测试客户、产品、授权和实例。</li>
|
||||
<li>交付:下载语言接入包;从实例页下载激活凭据与信任配置 JSON,通过受控渠道交付开发团队。</li>
|
||||
<li>联调:实现两个 JSON 的导入,先通过 ZIP 内测试向量,再验证激活、心跳、断网、到期及冻结行为。</li>
|
||||
<li>生产:在生产管理台重新创建实例并交付生产地址、公钥及绑定信息;使用生产凭据,核对公钥指纹,完成首次激活和心跳。</li>
|
||||
</ol>
|
||||
<p class="subheading">接入包提供协议和验签向量;各语言客户端 SDK、信任配置导入器仍由客户端工程实现。测试公钥、开发凭据不能带入生产。</p>
|
||||
<TrustDeliveryPanel />
|
||||
<div class="integration-controls">
|
||||
<label>目标语言 <select v-model="language" aria-label="目标语言"><option v-for="item in languages" :key="item.value" :value="item.value">{{ item.label }}</option></select></label>
|
||||
<label>接入模式 <select v-model="mode" aria-label="接入模式"><option v-for="item in modes" :key="item.value" :value="item.value">{{ item.label }}</option></select></label>
|
||||
@@ -55,7 +65,7 @@ onMounted(load)
|
||||
<h3>完整协议</h3>
|
||||
<details><summary>查看协议与验收要求</summary><pre class="vector-box">{{ kit.protocol }}</pre></details>
|
||||
<h3>首次激活凭据从哪里获取?</h3>
|
||||
<p>进入“License 授权”,签发授权后点击该行“实例”,选择“创建实例并获取激活凭据”。授权码是后台授权密钥(license_key);实例 ID(instance_id)和激活密钥(secret)由平台生成。每条授权仅绑定一个实例,secret 仅首次展示,请安全保存;之后仍用于心跳和下载。验签公钥由开发团队预置,不是管理员密码。</p>
|
||||
<p>进入“License 授权”,签发授权后点击该行“实例”,选择“创建实例并获取激活凭据”。授权码是后台授权密钥(license_key);实例 ID(instance_id)和激活密钥(secret)由平台生成。每条授权仅绑定一个实例,配置加密留存后可重复查看和下载,旧实例仅存哈希时无法恢复。secret 持续用于心跳和下载;验签公钥及实例绑定从管理台交付并由开发团队预置。</p>
|
||||
<h3>客户端升级方案</h3>
|
||||
<p class="subheading">当前支持已授权发布包下载;客户端版本检查、签名升级清单、灰度和升级回报仍待服务端建设,不能将其视为现有 API。</p>
|
||||
<details><summary>查看升级流程、安全边界与三种部署方案</summary><pre class="vector-box">{{ kit.upgrade }}</pre></details>
|
||||
|
||||
@@ -7,6 +7,7 @@ import AuditPanel from './AuditPanel.vue'
|
||||
import SettingsPanel from './SettingsPanel.vue'
|
||||
import AdminsPanel from './AdminsPanel.vue'
|
||||
import IntegrationPanel from './IntegrationPanel.vue'
|
||||
import TrustDeliveryPanel from './TrustDeliveryPanel.vue'
|
||||
import InstanceProvisionPanel from './InstanceProvisionPanel.vue'
|
||||
import { getSettings, type SiteSettings } from '../admin-api'
|
||||
const siteSettings = ref<SiteSettings|null>(null)
|
||||
@@ -121,7 +122,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>
|
||||
<ReleasesPanel v-if="pageView==='releases'" :products="products"/>
|
||||
<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 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>
|
||||
</main>
|
||||
</div></div>
|
||||
</template>
|
||||
|
||||
30
frontend/src/views/TrustDeliveryPanel.test.ts
Normal file
30
frontend/src/views/TrustDeliveryPanel.test.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import ElementPlus from 'element-plus'
|
||||
const calls = vi.hoisted(() => ({ getIntegrationTrust:vi.fn() }))
|
||||
vi.mock('../admin-api', async original => ({...await original<typeof import('../admin-api')>(),...calls}))
|
||||
import Panel from './TrustDeliveryPanel.vue'
|
||||
const trust={current_key_id:'current',keys:[{key_id:'current',public_key_pem:'PUBLIC PEM',revoked:false,spki_sha256:'abc'},{key_id:'old',public_key_pem:'OLD PEM',revoked:true,spki_sha256:'def'}]}
|
||||
beforeEach(()=>{vi.restoreAllMocks();calls.getIntegrationTrust.mockReset();calls.getIntegrationTrust.mockResolvedValue({data:{data:trust}})})
|
||||
it('exports instance binding and only unrevoked keys without credentials',async()=>{
|
||||
let content:unknown
|
||||
const blob=vi.spyOn(globalThis,'Blob').mockImplementation(function(parts){content=JSON.parse(String(parts![0]));return {} as Blob})
|
||||
Object.defineProperty(URL,'createObjectURL',{configurable:true,value:vi.fn(()=> 'blob:test')});Object.defineProperty(URL,'revokeObjectURL',{configurable:true,value:vi.fn()})
|
||||
vi.spyOn(HTMLAnchorElement.prototype,'click').mockImplementation(()=>{})
|
||||
const instance={id:1,instance_id:'instance-test',license_id:1,customer_id:3,product_id:4,status:'provisioned',created_at:'',freeze_state:'',observed_state:'',entitlement_state:''}
|
||||
const w=mount(Panel,{props:{instance},global:{plugins:[ElementPlus]}});await flushPromises()
|
||||
expect(w.text()).toContain('abc');expect(w.text()).toContain('客户 ID(customer_id):3')
|
||||
expect(w.findAll('button').filter(b=>b.text().includes('PEM')&&b.attributes('disabled')!==undefined)).toHaveLength(2)
|
||||
await w.get('input').setValue('https://license.example.com')
|
||||
await w.findAll('button').find(b=>b.text()==='下载实例信任配置 JSON')!.trigger('click')
|
||||
expect(content).toMatchObject({format:'yhy-license-trust',api_base_url:'https://license.example.com',instance_id:'instance-test',customer_id:3,product_id:4,keys:[trust.keys[0]]})
|
||||
expect(content).not.toHaveProperty('secret');expect(blob).toHaveBeenCalledTimes(1)
|
||||
await w.get('input').setValue('http://external.example.com');await w.findAll('button').find(b=>b.text()==='下载实例信任配置 JSON')!.trigger('click');expect(blob).toHaveBeenCalledTimes(1)
|
||||
w.unmount()
|
||||
})
|
||||
it('clears stale keys if refreshing fails',async()=>{
|
||||
const w=mount(Panel,{global:{plugins:[ElementPlus]}});await flushPromises();expect(w.text()).toContain('PUBLIC PEM')
|
||||
calls.getIntegrationTrust.mockRejectedValueOnce(new Error('未配置 v2 公钥环'))
|
||||
await w.findAll('button').find(b=>b.text()==='刷新公钥')!.trigger('click');await flushPromises()
|
||||
expect(w.text()).toContain('未配置 v2 公钥环');expect(w.text()).not.toContain('PUBLIC PEM');w.unmount()
|
||||
})
|
||||
62
frontend/src/views/TrustDeliveryPanel.vue
Normal file
62
frontend/src/views/TrustDeliveryPanel.vue
Normal file
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { getIntegrationTrust, type IntegrationTrust, type TrustKey } from '../admin-api'
|
||||
import type { LicenseInstance } from '../api'
|
||||
const props = defineProps<{ instance?: LicenseInstance }>()
|
||||
const trust = ref<IntegrationTrust|null>(null), loading = ref(false), error = ref('')
|
||||
const baseURL = ref(['localhost','127.0.0.1','[::1]'].includes(window.location.hostname) && window.location.port === '15173' ? `${window.location.protocol}//${window.location.hostname}:18081` : window.location.origin)
|
||||
async function load() {
|
||||
loading.value = true; error.value = ''; trust.value = null
|
||||
try { trust.value = (await getIntegrationTrust()).data.data }
|
||||
catch(e) { error.value = e instanceof Error ? e.message : '公钥加载失败' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
function download(name:string, content:string, type:string) {
|
||||
const url = URL.createObjectURL(new Blob([content], {type}))
|
||||
const link = document.createElement('a'); link.href = url; link.download = name
|
||||
document.body.appendChild(link)
|
||||
try { link.click() } finally { link.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000) }
|
||||
}
|
||||
async function copy(key:TrustKey) {
|
||||
try { await navigator.clipboard.writeText(key.public_key_pem); ElMessage.success('公钥已复制') }
|
||||
catch { ElMessage.error('复制失败,请手动选择 PEM') }
|
||||
}
|
||||
function exportTrust() {
|
||||
if (!trust.value || !props.instance) return
|
||||
try {
|
||||
const url = new URL(baseURL.value.trim())
|
||||
if (url.username || url.password || url.search || url.hash || url.pathname !== '/' ||
|
||||
(url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname)))) throw new Error('请输入 HTTPS 根地址;本机开发可使用 HTTP 回环地址')
|
||||
const keys = trust.value.keys.filter(k => !k.revoked)
|
||||
if (!keys.some(k => k.key_id === trust.value!.current_key_id)) throw new Error('当前签名密钥不可用,无法导出')
|
||||
const file = {format:'yhy-license-trust',version:1,api_base_url:url.origin,protocol_versions:['license-v2','lease-v2'],signature_algorithm:'ECDSA-P256-SHA256',current_key_id:trust.value.current_key_id,keys,instance_id:props.instance.instance_id,customer_id:props.instance.customer_id,product_id:props.instance.product_id}
|
||||
download(`trust-${props.instance.instance_id}.json`, JSON.stringify(file,null,2)+'\n','application/json;charset=utf-8')
|
||||
} catch(e) { ElMessage.error(e instanceof Error ? e.message : '导出失败') }
|
||||
}
|
||||
onMounted(load)
|
||||
</script>
|
||||
<template>
|
||||
<section class="data-section">
|
||||
<div class="section-heading"><h3>当前部署验签公钥</h3><el-button :loading="loading" @click="load">刷新公钥</el-button></div>
|
||||
<p class="subheading">开发和生产分别从对应管理台交付公钥,切勿混用。公钥可公开,私钥始终由服务器保管。客户端须经受控渠道预置信任,不能自动信任接口发现的新密钥。</p>
|
||||
<p v-if="error" class="error" role="alert">{{error}}</p>
|
||||
<template v-if="trust">
|
||||
<p>当前签名密钥:<code>{{trust.current_key_id}}</code></p>
|
||||
<article v-for="key in trust.keys" :key="key.key_id">
|
||||
<p><code>{{key.key_id}}</code> <el-tag :type="key.revoked?'danger':'success'">{{key.revoked?'已撤销':'未撤销'}}</el-tag> <span v-if="key.key_id===trust.current_key_id">当前签名</span></p>
|
||||
<p>SHA-256(SPKI DER):<code style="overflow-wrap:anywhere">{{key.spki_sha256}}</code></p>
|
||||
<pre class="vector-box">{{key.public_key_pem}}</pre>
|
||||
<el-button :disabled="key.revoked" @click="copy(key)">复制 PEM</el-button>
|
||||
<el-button :disabled="key.revoked" @click="download(`${key.key_id}.public.pem`,key.public_key_pem,'application/x-pem-file')">下载 PEM</el-button>
|
||||
</article>
|
||||
<template v-if="instance">
|
||||
<p>实例 ID:{{instance.instance_id}}<br>客户 ID(customer_id):{{instance.customer_id}}<br>产品 ID(product_id):{{instance.product_id}}</p>
|
||||
<label>授权中心根地址 <input v-model="baseURL" aria-label="信任配置授权中心地址" style="width:100%"></label>
|
||||
<p class="subheading">请确认地址。本机一键启动的 API 地址为 http://127.0.0.1:18081,浏览器前端端口不是 API 端口。导出仅含公钥和绑定信息;激活凭据另行交付。该格式需客户端实现导入,不会自动完成激活。</p>
|
||||
<el-button type="primary" @click="exportTrust">下载实例信任配置 JSON</el-button>
|
||||
</template>
|
||||
<p v-else class="subheading">在“授权 → 实例”下载绑定客户、产品和实例 ID 的信任配置 JSON。</p>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
Reference in New Issue
Block a user