feat: deliver client activation credentials and upgrade guidance
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 09:27:39 +08:00
parent 54c318c615
commit 099878dbba
13 changed files with 163 additions and 11 deletions

View File

@@ -142,6 +142,7 @@ func (a *BusinessAPI) provisionInstance(c *gin.Context) {
apiError(c, 500, "internal_error", "服务暂时不可用")
return
}
c.Header("Cache-Control", "no-store")
c.JSON(201, gin.H{"data": gin.H{"id": id, "instance_id": instanceID, "license_id": licenseID, "status": "provisioned", "secret": secret}, "secret_expires": "one-time"})
}

View File

@@ -72,11 +72,11 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
}
kit := buildIntegrationKit(language, mode)
files := map[string][]byte{
"README.md": []byte("# 客户端接入包\n\n阅读 protocol.md 与 openapi.json,将 prompt.md 提供给实现工程师。test-vectors.json 使用随机测试密钥,绝不能导入生产。此包提供文档和实现提示词,不是已完成生产验收的 SDK。\n"),
"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,
}
for _, name := range []string{"protocol.md", "openapi.json"} {
for _, name := range []string{"protocol.md", "upgrade.md", "openapi.json"} {
content, err := integrationAsset(name)
if err != nil {
apiError(c, 500, "internal_error", "接入资料不可用")
@@ -86,7 +86,7 @@ func (a *BusinessAPI) downloadIntegrationArchive(c *gin.Context) {
}
var buffer bytes.Buffer
archive := zip.NewWriter(&buffer)
for _, name := range []string{"README.md", "protocol.md", "openapi.json", "prompt.md", "test-vectors.json"} {
for _, name := range []string{"README.md", "protocol.md", "upgrade.md", "openapi.json", "prompt.md", "test-vectors.json"} {
file, err := archive.Create(name)
if err == nil {
_, err = file.Write(files[name])

View File

@@ -4,7 +4,13 @@
## 交付与激活
管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和一次性 secret。secret 无法从后台恢复;不得跨安装复制共享凭据。
管理员通过 POST /api/v1/licenses/{id}/instances 预置实例并交付 instance_id、license_key 和仅首次展示的 secret。secret 无法从后台恢复;它不是用完即失效的口令,激活后仍用于心跳与下载,必须安全持久化。不得跨安装复制共享凭据。
管理台操作:创建客户和产品 → 签发授权 → 在该授权行点击“实例” → “创建实例并获取激活凭据” → 安全保存并交付三个字段。当前每条授权只允许一个实例。
客户端字段对应:授权中心地址 = 实际部署 HTTPS 根地址(默认 https://license.example.com);实例 ID = instance_id(UUID,不是授权记录数字 ID);授权码 = license_key(后台“授权密钥”);激活密钥 = secret(平台生成的实例凭据,不是管理员密码、签名私钥或公钥)。生产验签公钥由开发团队通过受控渠道预置,不应要求最终用户填写。已激活客户端从受保护存储加载凭据,不应每次启动重复要求输入。
已有实例丢失 secret 时不能从列表读取;当前没有重置/轮换接口。由管理员冻结旧实例并撤销旧授权,再签发新授权、创建新实例并交付。旧离线租约不会立即失效,最长按现有租约策略持续 14 天。创建超时后先刷新实例列表核实结果,不能盲目反复创建。
POST /api/v1/activation/instances/{instance_id}

View File

@@ -0,0 +1,65 @@
# 客户端升级方案
## 当前能力与实施边界
默认平台根地址:https://license.example.com,可由 LICENSE_API_BASE_URL 覆盖。
当前可用:后台按产品发布版本包,记录 version、sha256、size_bytes;客户端通过 POST /api/v1/customers/{customer_id}/releases/{release_id}/download,JSON 提交 instance_id、secret,获得当前有权访问的包。下载时检查实例归属、产品、客户、授权有效期及冻结/撤销状态,并写入下载审计。发布包当前上限 64 MiB。
尚未实现:面向实例的版本发现、签名升级清单、平台/架构/渠道匹配、灰度及强制升级策略、安装器、健康检查及升级结果回报。GET /api/v1/products/{id}/releases 是管理员接口,客户端不能使用管理员账号或会话调用它。release_id 不代表版本大小顺序,现有版本字符串不保证符合 SemVer。
下载授权不等于代码可信。当前 X-Package-SHA256 可检测字节损坏,但它与包来自同一服务,不能替代独立签名。license-v2 / lease-v2 签名只证明授权和运行状态,不是升级包签名。当前实现不能宣称已支持安全无人值守自动升级。
## 第一阶段:受控人工升级(可复用现有下载接口)
发布负责人通过受控渠道向客户端交付目标 release_id、产品、版本、OS/架构、包长度和 SHA-256,并提供独立可信的包签名或平台代码签名校验方式。客户端使用已有实例身份下载,管理员凭据不得进入客户端。没有独立可信的签名/摘要时,仅允许管理员人工验证来源后安装,不启用自动执行。
下载必须经过配置了 X-Accel-Redirect internal 文件路由的 Nginx。直接调用 Go API 可能只有授权响应头而没有包体,不能将 HTTP 200 当成下载成功。校验实际长度与可信摘要;下载路由是带 JSON 凭据的 POST,不是公开 GET URL。禁止跟随跨域重定向转发 secret。
Range 续传依赖部署网关验证。每次续传仍发送 POST JSON 凭据;只有 206、Content-Range 起止与已下载偏移一致且总长度吻合时才能追加。若返回 200,截断临时文件重新下载,禁止追加完整响应。416 重新检查临时文件与目标版本。禁止让完整文件中的 HTTP 错误页进入安装流程。当前服务没有实现断点上传,下载续传能力须在实际网关验收。
## 第二阶段:自动升级所需服务端契约(设计,尚未实现)
建议新增实例认证的 POST /api/v1/instances/{instance_id}/updates/check。请求含 secret、product_id、current_version、current_release_sequence、platform、arch、channel、updater_version;服务端以实例关联产品为准,不信任客户端 product_id。返回无更新或已签名更新元数据。不得把这个设计地址当作现有接口调用,也不在当前 OpenAPI 中将其标记为可用。
签名元数据至少绑定 schema_version、product_id、release_id、release_sequence(产品/平台/架构/渠道范围内单调递增)、version、platform、arch、channel、package_format、size_bytes、sha256、published_at、expires_at、minimum_updater_version、minimum_supported_version、rollout_policy_version、mandatory、key_id 和 relative_download_path。relative_download_path 只能命中同源已有下载路由,不能是任意 URL。先验证签名、有效期、目标匹配、序号高水位和本地策略,再下载。
升级签名使用独立发布信任根与发布权限,不能直接复用授权签名私钥。优先采用成熟 TUF 实现,覆盖 root/targets/snapshot/timestamp、阈值签名、密钥轮换、元数据过期和版本一致性;平台代码签名作为额外校验。若另行实现简化签名,必须先冻结规范化字节、算法、key_id、信任根更新规则和跨语言向量,不能对 JSON 序列化输出随意签名。
升级清单中的 mandatory 只在完成真实性校验后才生效。离线时不因无法检查更新而立即阻断业务;运行权限仍由已验证授权租约决定。需要安全强制升级时,明确经过签名的最低支持版本、执行宽限期、离线策略和应急恢复流程。HTTP 错误不能被解释为可信的强制升级命令。
发布数据需要新增平台/架构/渠道、单调发布序号、签名清单、发布状态及灰度策略。稳定灰度分桶使用实例 ID 与服务端活动盐计算哈希,不使用每次随机命中。检查结果不能仅用时间戳或字符串比较决定版本,SemVer 要定义预发布版本与构建号规则。升级回报建议新增实例认证 POST /api/v1/instances/{instance_id}/updates/report,包含 attempt_id、from/to、阶段、结果和脱敏错误码,重复回报幂等;不能伪造尚未采集的成功率。
## 客户端状态机
空闲 → 检查 → 验证清单 → 等待批准/维护窗口 → 下载到临时目录 → 校验长度/哈希/签名 → 暂存 → 停止业务并安装 → 启动与健康检查 → 确认成功。
失败时保留可运行旧版本,记录失败版本和原因并进入退避,避免反复安装同一坏版本。为每次升级生成 attempt_id;使用跨进程锁防止多个更新器同时安装。网络重试不等于安装重试。持久化阶段日志,重启后能识别下载中、切换中、待确认和回滚状态。
健康失败触发回滚:停止新版本,切回最近一次已验证的健康版本,恢复兼容配置并重新启动。防回滚高水位仍保留,不接受远端下发更旧版本;本地故障回退只允许事务中保留的上一健康版本。服务端紧急恢复应发布更高序号的恢复版本,不能悄悄降低序号。
安装前检查磁盘(新包、解压、旧版本和备份所需空间)、权限、进程占用和路径。解压拒绝绝对路径、..、符号链接/硬链接越界及解压炸弹,设置文件数和解压总量上限。跨卷 rename 不保证原子,暂存与目标放在同卷;文件替换、目录切换和日志持久化必须按 OS 验证断电恢复。实例 ID、secret、授权证书与租约存于独立受保护状态目录,升级不可重新初始化或随包覆盖。
数据库迁移采用先兼容旧版本的 expand,再切换代码,最后在回退窗口结束后 contract。不能回滚数据库的升级禁止宣称一键自动回退;先备份并验证恢复方案。新程序健康检查包括启动、版本确认、关键业务和本地状态可读,不能只验证进程存活。
## 桌面客户端
使用独立更新器或安装器,主程序完成下载校验后提示用户保存工作,退出并等待进程结束,再由更新器安装。Windows 文件占用时不能让程序直接覆盖自己的 EXE;验证 Authenticode/安装包签名,并限制提权。macOS 验证 Developer ID、代码签名及公证,Linux 验证发布签名。启动新版本并握手确认实际运行版本与健康状态;失败恢复旧版本。自动下载和自动安装分别由用户策略控制。
## 常驻服务
由独立 supervisor、systemd 或 Windows Service 管理更新。使用版本目录与可恢复的入口切换,先摘流量、等待在途任务结束,再停止、切换、启动、探活。集群滚动更新限制并发与不可用实例数;严格约定任务幂等及共享存储兼容性。更新器权限最小化,维护窗口决定安装时机。安装失败优先恢复旧实例提供服务。
## 容器部署
容器内应用不得下载包覆盖自身程序,不挂载 Docker socket 给业务容器。升级由 CI/CD、Kubernetes 或受控部署代理执行;固定镜像 digest,验镜像签名/来源并使用 registry 凭据。先 readiness 再滚动替换,保留旧 digest、配置及持久化状态以便回退。现有二进制下载接口不是容器镜像仓库;镜像发布、灰度与部署回报是另行建设的能力。实例身份与 secret 由独立卷/Secret 注入,副本身份规则需要显式定义。
## 错误和重试策略
403:无下载权限,暂停此次升级并检查授权,不自动删除已验证运行租约。409:检查状态冲突,人工或业务决策后再尝试。429:遵守 Retry-After。网络/5xx:有限次数指数退避加抖动,不泄露 secret。签名、长度、哈希、架构或发布序号失败:立即丢弃暂存包并禁止安装;当前健康版本继续按照授权租约规则运行。取消和超时不覆盖当前版本。
## 验收清单
覆盖:完整升级;无更新;错误产品/OS/架构/渠道;损坏包与签名篡改;未知/撤销发布密钥;过期元数据;旧序号重放;网络中断及 200/206/416 续传;无 Nginx 包体;磁盘不足;恶意解压路径;并发更新锁;进程占用;安装中断电恢复;新版本探活失败与本地回退;数据库不兼容阻止安装;升级后 instance_id/secret/租约保留;冻结/撤销阻止新下载;回报幂等与日志脱敏。容器另验固定 digest、验签、滚动健康与恢复旧 digest。
接入团队交付 UpdateClient、受控包验证器、独立安装器/部署适配器、持久化升级状态及跨进程锁、健康与回退策略、上述负向测试。第一阶段只对现有下载接口实现适配;第二阶段契约完成前,版本发现和签名元数据通过可注入接口模拟,明确标记待接平台,不得伪装成生产可调用 API。

View File

@@ -40,6 +40,7 @@ type integrationKitResponse struct {
Prompt string `json:"prompt"`
TestVector kitVector `json:"payload_example"`
Protocol string `json:"protocol"`
Upgrade string `json:"upgrade"`
}
type kitAPI struct {
@@ -73,6 +74,7 @@ func integrationKitInput(c *gin.Context) (string, string, bool) {
func buildIntegrationKit(language, mode string) integrationKitResponse {
label, modeLabel := integrationLanguages[language], integrationModes[mode]
protocol, _ := integrationAsset("protocol.md")
upgrade, _ := integrationAsset("upgrade.md")
return integrationKitResponse{
ProtocolVersion: "license-v2 / lease-v2",
PlatformBaseURL: defaultIntegrationBaseURL,
@@ -94,7 +96,8 @@ func buildIntegrationKit(language, mode string) integrationKitResponse {
"403/409 进入不可用或人工处理状态;429 遵循 Retry-After;不得无限自动重试。",
},
Protocol: string(protocol),
Prompt: integrationPrompt(label, modeLabel) + "\n\n" + languageRequirements(language) + "\n\n必须阅读接入包 protocol.md 与 openapi.json。签名规范化不是 JSON:固定顺序 key=value、LF 连接、UTF-8、无末尾换行;签名是 DER ECDSA 的无填充标准 Base64。先通过包内随机测试公钥的 license-v2 和 lease-v2 验签向量,再连接部署环境。测试公钥不得在生产中信任。",
Upgrade: string(upgrade),
Prompt: integrationPrompt(label, modeLabel) + "\n\n" + languageRequirements(language) + "\n\n必须阅读接入包 protocol.md、upgrade.md 与 openapi.json。签名规范化不是 JSON:固定顺序 key=value、LF 连接、UTF-8、无末尾换行;签名是 DER ECDSA 的无填充标准 Base64。先通过包内随机测试公钥的 license-v2 和 lease-v2 验签向量,再连接部署环境。测试公钥不得在生产中信任。\n\n客户端升级:当前仅可复用已授权发布包下载,尚未实现客户端版本检查或签名升级清单。先按 upgrade.md 的第一阶段完成受控人工升级;自动升级必须等待第二阶段升级元数据、独立发布信任根和灰度策略落地。",
TestVector: kitVector{
Version: "lease-v2", InstanceID: "11111111-2222-3333-4444-555555555555", State: "active",
ServerTime: "2026-10-09T03:00:00Z", EntitlementExpiresAt: "2027-10-09T03:00:00Z", LeaseExpiresAt: "2026-10-23T03:00:00Z",
@@ -115,6 +118,8 @@ func integrationPrompt(language, mode string) string {
默认授权平台根地址:%s。将它作为 SDK 的默认值,同时允许部署通过 LICENSE_API_BASE_URL 覆盖;配置为根地址,不要附加 /api/v1,不要在业务代码中散落硬编码 URL。
首次设置由管理员在“授权 → 实例 → 创建实例并获取激活凭据”交付 instance_id、license_key、secret。UI 字段统一为“实例 ID”“授权码”“激活密钥”。实例 ID 不是数据库数字 ID;授权码是后台授权密钥;secret 仅首次展示但持续用于心跳和下载。公钥通过受控渠道预置,管理员密码与私钥绝不能要求最终用户输入。已激活后从受保护存储恢复,不要每次启动重新填写。当前每条授权只绑定一个实例,丢失 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。
必须使用受控渠道预置的 ECDSA P-256 公钥验证 license-v2 / lease-v2 信封,验证 key_id、version、instance_id、state、entitlement_expires_at、lease_expires_at。仅 active 且授权/租约均未过期时允许业务运行。持久化并原子更新已接受租约及本地、服务端时间高水位。secret 不得写入 URL、日志、异常、镜像或源码;403/409 停止自动重试,429 遵循 Retry-After。
@@ -147,7 +152,7 @@ func (a *BusinessAPI) downloadIntegrationKit(c *gin.Context) {
fmt.Fprintf(&b, "- %s\n", rule)
}
fmt.Fprintf(&b, "\n## 租约字段示例(不是签名测试向量)\n\n```json\n{\n \"version\": \"%s\",\n \"instance_id\": \"%s\",\n \"state\": \"%s\",\n \"server_time\": \"%s\",\n \"entitlement_expires_at\": \"%s\",\n \"lease_expires_at\": \"%s\"\n}\n```\n", kit.TestVector.Version, kit.TestVector.InstanceID, kit.TestVector.State, kit.TestVector.ServerTime, kit.TestVector.EntitlementExpiresAt, kit.TestVector.LeaseExpiresAt)
fmt.Fprintf(&b, "\n\n%s\n", kit.Protocol)
fmt.Fprintf(&b, "\n\n%s\n\n%s\n", kit.Protocol, kit.Upgrade)
c.Header("Cache-Control", "no-store")
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=license-platform-%s-%s-integration.md", language, mode))
c.Data(http.StatusOK, "text/markdown; charset=utf-8", []byte(b.String()))

View File

@@ -40,7 +40,7 @@ func TestIntegrationInputs(t *testing.T) {
}
for language := range integrationLanguages {
kit := buildIntegrationKit(language, "service")
if !strings.Contains(kit.Prompt, languageRequirements(language)) || !strings.Contains(kit.Prompt, defaultIntegrationBaseURL) || !strings.Contains(kit.Protocol, defaultIntegrationBaseURL) || kit.PlatformBaseURL != defaultIntegrationBaseURL || !strings.Contains(kit.Protocol, "DER") {
if !strings.Contains(kit.Prompt, languageRequirements(language)) || !strings.Contains(kit.Prompt, defaultIntegrationBaseURL) || !strings.Contains(kit.Protocol, defaultIntegrationBaseURL) || kit.PlatformBaseURL != defaultIntegrationBaseURL || !strings.Contains(kit.Protocol, "DER") || !strings.Contains(kit.Upgrade, "当前能力与实施边界") || !strings.Contains(kit.Prompt, "尚未实现客户端版本检查") {
t.Fatal("incomplete kit")
}
}
@@ -68,7 +68,7 @@ func TestIntegrationArchiveAndSignatures(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(archive.File) != 5 {
if len(archive.File) != 6 {
t.Fatal("missing files")
}
for _, file := range archive.File {
@@ -84,6 +84,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 == "upgrade.md" && !strings.Contains(string(content), "自动升级所需服务端契约") {
t.Fatal("missing upgrade plan")
}
if file.Name != "test-vectors.json" {
continue
}

View File

@@ -32,3 +32,9 @@ SDK 与工程提示词默认使用 `https://license.yihuiyong.cn` 作为授权
- 浏览器实际切换 .NET:专属 DER 格式提示与下载 URL 更新。390×844 窄屏无整体横向溢出,控制台 0 error。
未迁移或修改原业务数据库,未提交或推送代码。现有大包构建提示与旧测试的组件 stub 警告仍存在。全仓 `git diff --check` 的两项旧文档末尾空行不在本次功能范围内。
## 首次激活交付与客户端字段
管理员创建客户/产品并签发授权后,在“License 授权 → 实例 → 创建实例并获取激活凭据”预置实例。授权码对应 license_key(授权密钥),实例 ID 对应 instance_id(UUID),激活密钥对应 secret。平台目前每条授权只绑定一个实例。secret 只在创建响应及当前窗口展示,数据库保存哈希,关闭后无法恢复;该凭据激活后仍用于心跳和下载。创建超时先刷新实例列表核实,不自动重试。丢失凭据需冻结旧实例、撤销旧授权,再签发新授权交付新实例;旧离线租约最多仍可生效 14 天。客户端不应让用户填写管理员密码或签名私钥,公钥通过受控渠道预置;激活后加载受保护状态,不要求每次启动填写。
升级方案随 JSON、Markdown 和 ZIP 导出,ZIP 新增 upgrade.md(共六个文件)。实例创建响应设置 Cache-Control: no-store;前端不将 secret 写入日志或浏览器持久化存储。

View File

@@ -20,6 +20,7 @@ export type IntegrationKit = {
protocol_version:string; platform_base_url:string; language:IntegrationLanguage; language_label:string; mode:IntegrationMode; mode_label:string
endpoints:{method:string;path:string;purpose:string}[]; security_rules:string[]; prompt:string
protocol:string
upgrade:string
payload_example:{version:string;instance_id:string;state:string;server_time:string;entitlement_expires_at:string;lease_expires_at:string}
}
export const getIntegrationKit = (language:IntegrationLanguage, mode:IntegrationMode) => api.get<{data:IntegrationKit}>('/integration-kit', {params:{language,mode}})

View File

@@ -28,3 +28,5 @@ export async function listLicenseInstances(id:number) { return api.get<{data:Lic
export async function getLicense(id:number) { return api.get<{data:License}>(`/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}}) }
export async function provisionLicenseInstance(id:number) { return api.post<{data:{id:number;instance_id:string;license_id:number;status:string;secret:string}}>(`/licenses/${id}/instances`,{}) }

View File

@@ -0,0 +1,22 @@
import { beforeEach, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import ElementPlus, { ElMessageBox } from 'element-plus'
const api=vi.hoisted(()=>({getLicense:vi.fn(),provisionLicenseInstance:vi.fn()}))
vi.mock('../api',()=>api)
import Panel from './InstanceProvisionPanel.vue'
beforeEach(()=>{vi.restoreAllMocks();vi.resetAllMocks();vi.spyOn(ElMessageBox,'confirm').mockResolvedValue('confirm' as Awaited<ReturnType<typeof ElMessageBox.confirm>>);api.getLicense.mockResolvedValue({data:{data:{license_key:'test-license'}}});api.provisionLicenseInstance.mockResolvedValue({data:{data:{instance_id:'test-instance',secret:'test-secret'}}})})
it('creates and displays first-return credentials, without another creation entry',async()=>{
const w=mount(Panel,{props:{licenseId:7,hasInstance:false,ready:true},global:{plugins:[ElementPlus]}})
await w.get('button').trigger('click');await flushPromises()
expect(api.provisionLicenseInstance).toHaveBeenCalledWith(7)
expect(w.text()).toContain('test-license');expect(w.text()).toContain('test-instance');expect(w.text()).toContain('test-secret');expect(w.emitted('created')).toHaveLength(1)
expect(w.find('button').exists()).toBe(false);w.unmount()
const reopened=mount(Panel,{props:{licenseId:7,hasInstance:true,ready:true},global:{plugins:[ElementPlus]}})
expect(reopened.get('button').attributes('disabled')).toBeDefined();expect(reopened.text()).not.toContain('test-secret');reopened.unmount()
})
it('reports uncertain creation without automatically retrying',async()=>{
api.provisionLicenseInstance.mockRejectedValue(new Error('请求超时'))
const w=mount(Panel,{props:{licenseId:7,hasInstance:false,ready:true},global:{plugins:[ElementPlus]}})
await w.get('button').trigger('click');await flushPromises()
expect(w.text()).toContain('先刷新实例列表');expect(api.provisionLicenseInstance).toHaveBeenCalledTimes(1);w.unmount()
})

View File

@@ -0,0 +1,35 @@
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import { getLicense, provisionLicenseInstance } from '../api'
const props = defineProps<{licenseId:number;hasInstance:boolean;ready:boolean}>()
const emit = defineEmits<{created:[]}>()
const busy = ref(false), error = ref('')
const credentials = ref<{instance_id:string;license_key:string;secret:string}|null>(null)
async function create() {
if(busy.value || props.hasInstance || !props.ready || credentials.value || error.value) return
try { await ElMessageBox.confirm('每条授权只能绑定一个实例。激活密钥仅在创建成功时显示,请立即通过安全渠道保存并交付。确认创建?','创建客户端实例') } catch { return }
busy.value=true;error.value=''
try {
const license=(await getLicense(props.licenseId)).data.data
const result=(await provisionLicenseInstance(props.licenseId)).data.data
credentials.value={instance_id:result.instance_id,license_key:license.license_key,secret:result.secret}
emit('created')
} catch(e) { error.value=(e instanceof Error?e.message:'创建失败')+'。若请求超时,请先刷新实例列表确认是否已创建;密钥无法再次获取,请勿反复创建。' }
finally { busy.value=false }
}
</script>
<template>
<section class="data-section">
<h3>客户端激活凭据</h3>
<p>授权码就是授权密钥(license_key)。实例 ID 和激活密钥(secret)由平台创建实例时生成,每条授权仅绑定一个实例。</p>
<el-button v-if="!credentials" type="primary" :loading="busy" :disabled="!ready||hasInstance||!!error" @click="create">创建实例并获取激活凭据</el-button>
<p v-if="hasInstance&&!credentials" class="subheading">已有实例的激活密钥无法再次查看。若未安全保存,请由管理员冻结旧实例、撤销旧授权,再签发新授权并交付新实例凭据;当前不支持密钥找回或轮换。</p>
<p v-if="error" class="error" role="alert">{{error}}</p>
<template v-if="credentials">
<p role="status">实例已创建。请立即安全保存下列凭据,关闭窗口后不再显示激活密钥。</p>
<dl class="license-detail"><dt>实例 ID(instance_id)</dt><dd class="license-code">{{credentials.instance_id}}</dd><dt>授权码(license_key)</dt><dd class="license-code">{{credentials.license_key}}</dd><dt>激活密钥(secret)</dt><dd class="license-code">{{credentials.secret}}</dd></dl>
<p>默认授权中心:https://license.yihuiyong.cn;私有部署填写实际 HTTPS 根地址。密钥仅首次展示,但客户端激活后仍需安全保存用于心跳和下载;不要放入日志、截图或普通工单。生产验签公钥应由开发团队预置。</p>
</template>
</section>
</template>

View File

@@ -35,7 +35,7 @@ onMounted(load)
</script>
<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>
<div class="section-heading"><div><h2>客户端接入包</h2><p>选择目标语言和运行方式,交付给外部工程团队实现客户端 SDK 与升级能力。</p></div><el-button :loading="loading" @click="load">刷新资料</el-button></div>
<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>
@@ -54,6 +54,11 @@ onMounted(load)
<ul class="integration-rules"><li v-for="rule in kit.security_rules" :key="rule">{{ rule }}</li></ul>
<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>
<h3>客户端升级方案</h3>
<p class="subheading">当前支持已授权发布包下载;客户端版本检查、签名升级清单、灰度和升级回报仍待服务端建设,不能将其视为现有 API。</p>
<details><summary>查看升级流程、安全边界与三种部署方案</summary><pre class="vector-box">{{ kit.upgrade }}</pre></details>
<h3>租约字段示例</h3>
<pre class="vector-box">{{ JSON.stringify(kit.payload_example, null, 2) }}</pre>
<p class="subheading">签名测试向量及独立测试公钥包含在 ZIP 中,禁止将测试公钥加入生产信任配置。</p>

View File

@@ -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 InstanceProvisionPanel from './InstanceProvisionPanel.vue'
import { getSettings, type SiteSettings } from '../admin-api'
const siteSettings = ref<SiteSettings|null>(null)
async function loadSiteSettings() { try { siteSettings.value = (await getSettings()).data.data } catch { siteSettings.value = null } }
@@ -117,10 +118,10 @@ 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>
<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==='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></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)"><el-button :loading="instancesLoading" @click="selectedLicenseID !== null && showInstances(selectedLicenseID)">刷新状态</el-button><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 prop="status" label="激活状态"/><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!)"/><el-button :loading="instancesLoading" @click="selectedLicenseID !== null && showInstances(selectedLicenseID)">刷新状态</el-button><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 prop="status" label="激活状态"/><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>