feat(protect): 加壳产物落成新版本记录

- Version 新增 protected / source_version_id / protect_task_id,ProtectTask 新增 version_id
- protect.PublishAsVersion:产物写入内容寻址存储、复制来源版本其余文件、版本号可自动进位
- 路由 POST /dev/protect/tasks/:id/publish、MCP 工具 verify_publish_protected_version
- 面板任务行加「生成版本」弹窗(版本号/策略/更新说明/立即发布)
- 单测 BumpVersion
This commit is contained in:
hermes
2026-11-21 15:19:56 +08:00
parent 22570341ef
commit 02df87f464
9 changed files with 479 additions and 3 deletions
+4
View File
@@ -246,6 +246,9 @@ type Version struct {
PublishedAt *time.Time `json:"published_at"`
DeprecatedAt *time.Time `json:"deprecated_at"`
BaseVersionID *uint `json:"base_version_id"`
Protected bool `gorm:"default:false" json:"protected"` // 是否为加壳产物
SourceVersionID *uint `gorm:"index" json:"source_version_id"` // 加壳来源版本
ProtectTaskID *uint `json:"protect_task_id"` // 对应加壳任务
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
@@ -895,6 +898,7 @@ type ProtectTask struct {
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"index" json:"application_id"`
UserID uint `gorm:"index" json:"user_id"`
VersionID uint `gorm:"index" json:"version_id"` // 来源版本(从哪个版本加壳)
SourceName string `gorm:"size:255" json:"source_name"`
SourceSize int64 `json:"source_size"`
Arch string `gorm:"size:16" json:"arch"`
+200
View File
@@ -0,0 +1,200 @@
package protect
// 把加壳产物落成一条新版本记录:客户端按「版本记录 ID 递增」判定更新,
// 原地改已发布版本的入口文件在客户端不报 manifest_hash 时永远推不下去。
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/utils/contentstore"
)
// PublishOptions 生成版本的参数
type PublishOptions struct {
Version string // 留空则按来源版本自动进位
UpdateStrategy string // optional / forced(默认 optional)
UpdateType string // full / delta(默认 full)
UpdateMethod string // auto / manual(默认 auto)
Changelog string
PublishNow bool // 建好就直接发布
}
// PublishAsVersion 把任务产物写成新版本,返回创建出的版本
func PublishAsVersion(taskID uint, opts PublishOptions) (*model.Version, error) {
var task model.ProtectTask
if err := database.DB.First(&task, taskID).Error; err != nil {
return nil, fmt.Errorf("加壳任务不存在")
}
if task.Status != "done" || task.OutputPath == "" {
return nil, fmt.Errorf("任务尚未完成,无法生成版本")
}
data, err := os.ReadFile(task.OutputPath)
if err != nil {
return nil, fmt.Errorf("读取产物失败: %w", err)
}
var app model.Application
if err := database.DB.First(&app, task.ApplicationID).Error; err != nil {
return nil, fmt.Errorf("应用不存在")
}
sum := sha256.Sum256(data)
hash := hex.EncodeToString(sum[:])
stored := contentstore.ContentFilePath(hash)
if stored == "" {
return nil, fmt.Errorf("内容哈希异常")
}
if err := os.MkdirAll(filepath.Dir(stored), 0o755); err != nil {
return nil, err
}
if err := os.WriteFile(stored, data, 0o644); err != nil {
return nil, fmt.Errorf("落盘产物失败: %w", err)
}
var src model.Version
hasSrc := task.VersionID > 0 && database.DB.First(&src, task.VersionID).Error == nil
versionStr := strings.TrimSpace(opts.Version)
if versionStr == "" {
switch {
case hasSrc:
versionStr = BumpVersion(src.Version)
default:
// 不是从某个版本加壳的(面板直传),就按应用当前最高版本进位
var latest model.Version
if database.DB.Where("application_id = ?", app.ID).Order("id DESC").First(&latest).Error == nil {
versionStr = BumpVersion(latest.Version)
} else {
versionStr = time.Now().Format("2006.01.02.1504")
}
}
}
var dup int64
database.DB.Model(&model.Version{}).
Where("application_id = ? AND version = ?", app.ID, versionStr).Count(&dup)
if dup > 0 {
return nil, fmt.Errorf("版本号 %s 已存在,请换一个", versionStr)
}
strategy := opts.UpdateStrategy
if strategy == "" {
strategy = "optional"
}
if strategy != "optional" && strategy != "forced" {
return nil, fmt.Errorf("update_strategy 只能是 optional 或 forced")
}
updateType := opts.UpdateType
if updateType == "" {
updateType = "full"
}
method := opts.UpdateMethod
if method == "" {
method = "auto"
}
entryName := filepath.Base(task.OutputName)
if entryName == "" {
entryName = "app_protected.exe"
}
srcID := task.VersionID
taskIDCopy := task.ID
v := model.Version{
ApplicationID: app.ID,
Version: versionStr,
FilePath: stored,
FileSize: int64(len(data)),
FileHash: hash,
EntryFile: entryName,
UpdateStrategy: strategy,
UpdateType: updateType,
UpdateMethod: method,
Changelog: opts.Changelog,
PublishStatus: "draft",
Protected: true,
ProtectTaskID: &taskIDCopy,
}
if srcID > 0 {
v.SourceVersionID = &srcID
}
if opts.PublishNow {
now := time.Now()
v.PublishStatus = "published"
v.PublishedAt = &now
}
if err := database.DB.Create(&v).Error; err != nil {
return nil, fmt.Errorf("创建版本失败: %w", err)
}
// 入口文件(加壳产物)
vf := model.VersionFile{
VersionID: v.ID,
FileName: entryName,
FilePath: contentstore.ContentFileURL(hash),
FileSize: int64(len(data)),
FileHash: hash,
FileType: "program",
IsRequired: true,
SortOrder: 0,
}
if err := database.DB.Create(&vf).Error; err != nil {
return nil, fmt.Errorf("写入版本文件失败: %w", err)
}
// 其余资源文件沿用来源版本(内容寻址,不重复占空间)
if hasSrc {
var srcFiles []model.VersionFile
database.DB.Where("version_id = ?", src.ID).Find(&srcFiles)
for _, f := range srcFiles {
if strings.EqualFold(filepath.Base(f.FileName), entryName) {
continue
}
if strings.EqualFold(filepath.Base(f.FileName), filepath.Base(src.EntryFile)) {
continue
}
cp := model.VersionFile{
VersionID: v.ID, FileName: f.FileName, FilePath: f.FilePath,
FileSize: f.FileSize, FileHash: f.FileHash, FileType: f.FileType,
IsRequired: f.IsRequired, SortOrder: f.SortOrder + 1,
}
database.DB.Create(&cp)
}
}
if opts.PublishNow && strategy == "forced" {
database.DB.Model(&model.Version{}).
Where("application_id = ? AND id < ? AND publish_status = ?", app.ID, v.ID, "published").
Updates(map[string]interface{}{
"publish_status": "superseded",
"superseded_by": v.ID,
"deprecated_at": time.Now(),
})
}
database.DB.Model(&model.ProtectTask{}).Where("id = ?", task.ID).
Update("version_id", v.ID)
return &v, nil
}
// BumpVersion 末段数字 +1:1.1.13 → 1.1.14;无数字则追加 .1
func BumpVersion(v string) string {
v = strings.TrimSpace(v)
if v == "" {
return "1.0.0"
}
parts := strings.Split(v, ".")
last := parts[len(parts)-1]
if n, err := strconv.Atoi(last); err == nil {
parts[len(parts)-1] = strconv.Itoa(n + 1)
return strings.Join(parts, ".")
}
return v + ".1"
}
+20
View File
@@ -0,0 +1,20 @@
package protect
import "testing"
func TestBumpVersion(t *testing.T) {
cases := map[string]string{
"1.1.13": "1.1.14",
"9.9.9": "9.9.10",
"2": "3",
"v1.2.3": "v1.2.4",
"1.0.0.99": "1.0.0.100",
"beta": "beta.1",
"": "1.0.0",
}
for in, want := range cases {
if got := BumpVersion(in); got != want {
t.Fatalf("BumpVersion(%q) = %q, 期望 %q", in, got, want)
}
}
}
+9
View File
@@ -95,10 +95,19 @@ func CreateAndRun(app *model.Application, userID uint, srcName string, data []by
// CreateAndRunSync 同步加壳(MCP 这类需要立刻拿到结果调用方用)
func CreateAndRunSync(app *model.Application, userID uint, srcName string, data []byte, baseURL string) (*model.ProtectTask, Info, error) {
return CreateAndRunSyncWithVersion(app, userID, srcName, data, baseURL, 0)
}
// CreateAndRunSyncWithVersion 同步加壳并记录来源版本(versionID 可为 0)
func CreateAndRunSyncWithVersion(app *model.Application, userID uint, srcName string, data []byte, baseURL string, versionID uint) (*model.ProtectTask, Info, error) {
task, srcPath, err := createTask(app, userID, srcName, data)
if err != nil {
return task, Info{}, err
}
if versionID > 0 && task != nil {
database.DB.Model(task).Update("version_id", versionID)
task.VersionID = versionID
}
info, err := execute(task.ID, srcPath, srcName, BuildCfg(app.AppKey, app.Name, baseURL))
if err != nil {
return task, info, err
+49
View File
@@ -25,6 +25,7 @@ func SetupProtectRoutes(r *gin.RouterGroup) {
g.GET("/tasks", HandleListProtectTasks)
g.GET("/tasks/:id", HandleGetProtectTask)
g.GET("/tasks/:id/download", HandleDownloadProtectTask)
g.POST("/tasks/:id/publish", HandlePublishProtectTask)
g.DELETE("/tasks/:id", HandleDeleteProtectTask)
}
}
@@ -157,6 +158,54 @@ func HandleDownloadProtectTask(c *gin.Context) {
c.FileAttachment(task.OutputPath, task.OutputName)
}
// HandlePublishProtectTask 把加壳产物落成一条新版本记录
func HandlePublishProtectTask(c *gin.Context) {
userID := c.GetUint("user_id")
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var task model.ProtectTask
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
response.NotFound(c, "任务不存在")
return
}
var body struct {
Version string `json:"version"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
Changelog string `json:"changelog"`
PublishNow bool `json:"publish_now"`
}
if err := c.ShouldBindJSON(&body); err != nil {
response.ParamError(c, "参数格式错误")
return
}
version, err := protect.PublishAsVersion(task.ID, protect.PublishOptions{
Version: body.Version,
UpdateStrategy: body.UpdateStrategy,
UpdateType: body.UpdateType,
UpdateMethod: body.UpdateMethod,
Changelog: body.Changelog,
PublishNow: body.PublishNow,
})
if err != nil {
response.Error(c, 400, err.Error())
return
}
response.SuccessWithMessage(c, "已生成版本", gin.H{
"version_id": version.ID,
"version": version.Version,
"publish_status": version.PublishStatus,
"entry_file": version.EntryFile,
"file_size": version.FileSize,
"file_hash": version.FileHash,
"protected": version.Protected,
})
}
// HandleDeleteProtectTask 删除任务(含源文件与产物)
func HandleDeleteProtectTask(c *gin.Context) {
userID := c.GetUint("user_id")
+70 -1
View File
@@ -607,7 +607,7 @@ func registerWriteTools(s *mcpserver.MCPServer) {
return sdk.NewToolResultError("缺少 base_url:请传参或配置 protect.base_url(产物靠它找到验证接口)"), nil
}
task, info, err := protect.CreateAndRunSync(&app, app.UserID, chosen.FileName, data, base)
task, info, err := protect.CreateAndRunSyncWithVersion(&app, app.UserID, chosen.FileName, data, base, v.ID)
if err != nil {
return sdk.NewToolResultErrorFromErr("加壳失败", err), nil
}
@@ -618,6 +618,75 @@ func registerWriteTools(s *mcpserver.MCPServer) {
"entry_old": fmt.Sprintf("0x%x", info.EntryOld), "entry_new": fmt.Sprintf("0x%x", info.EntryNew),
"crc_vfy": fmt.Sprintf("%08x", info.CrcVfy), "crc_file": fmt.Sprintf("%08x", info.CrcFile),
"download": fmt.Sprintf("/api/v1/dev/protect/tasks/%d/download", task.ID),
"next": "调 verify_publish_protected_version 把产物落成新版本",
})
})
// ---------- 把加壳产物落成版本 ----------
s.AddTool(sdk.NewTool("verify_publish_protected_version",
sdk.WithDescription("把已完成的加壳任务产物写成一条新的版本记录(客户端按版本记录 ID 递增判定更新,原地改已发布版本的入口文件推不下去)。其余资源文件沿用来源版本;版本号留空则末段自动 +1。dry_run=true 只报告将创建的版本。"),
sdk.WithDestructiveHintAnnotation(true),
sdk.WithNumber("task_id", sdk.Required(), sdk.Description("加壳任务 ID")),
sdk.WithString("version", sdk.Description("新版本号,留空自动进位")),
sdk.WithString("update_strategy", sdk.Description("optional / forced,默认 optional")),
sdk.WithString("update_type", sdk.Description("full / delta,默认 full")),
sdk.WithString("changelog", sdk.Description("更新说明")),
sdk.WithBoolean("publish_now", sdk.Description("创建后立即发布,默认 false(存为草稿)")),
sdk.WithBoolean("dry_run", sdk.Description("只报告不改动,默认 true")),
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
tid := req.GetInt("task_id", 0)
if tid <= 0 {
return sdk.NewToolResultError("task_id 必须为正整数"), nil
}
var task model.ProtectTask
if err := database.DB.First(&task, tid).Error; err != nil {
return sdk.NewToolResultError("加壳任务不存在"), nil
}
if task.Status != "done" {
return sdk.NewToolResultError("任务未完成,当前状态: " + task.Status), nil
}
opts := protect.PublishOptions{
Version: req.GetString("version", ""),
UpdateStrategy: req.GetString("update_strategy", "optional"),
UpdateType: req.GetString("update_type", "full"),
Changelog: req.GetString("changelog", ""),
PublishNow: req.GetBool("publish_now", false),
}
if opts.Version == "" && task.VersionID > 0 {
var src model.Version
if database.DB.First(&src, task.VersionID).Error == nil {
opts.Version = protect.BumpVersion(src.Version)
}
}
if req.GetBool("dry_run", true) {
var srcInfo gin.H
if task.VersionID > 0 {
var src model.Version
if database.DB.First(&src, task.VersionID).Error == nil {
srcInfo = gin.H{"source_version_id": src.ID, "source_version": src.Version, "source_publish_status": src.PublishStatus}
}
}
return sdk.NewToolResultJSON(gin.H{
"dry_run": true, "task_id": task.ID, "application_id": task.ApplicationID,
"source_name": task.SourceName, "output_name": task.OutputName,
"output_size": task.OutputSize, "arch": task.Arch,
"planned_version": opts.Version, "update_strategy": opts.UpdateStrategy,
"publish_now": opts.PublishNow, "source": srcInfo,
})
}
v, err := protect.PublishAsVersion(task.ID, opts)
if err != nil {
return sdk.NewToolResultErrorFromErr("生成版本失败", err), nil
}
return sdk.NewToolResultJSON(gin.H{
"dry_run": false, "version_id": v.ID, "version": v.Version,
"publish_status": v.PublishStatus, "entry_file": v.EntryFile,
"file_size": v.FileSize, "file_hash": v.FileHash,
"protected": v.Protected, "source_version_id": v.SourceVersionID,
"update_strategy": v.UpdateStrategy,
})
})
}
@@ -163,6 +163,37 @@ function downloadTask(task: Task) {
window.open(`${BASE_URL}/dev/protect/tasks/${task.id}/download?token=${token}`, '_blank')
}
// ---- 生成版本 ----
const publishOpen = ref(false)
const publishing = ref(false)
const publishTask = ref<Task | null>(null)
const publishForm = ref({ version: '', update_strategy: 'optional', changelog: '', publish_now: false })
function openPublish(task: Task) {
publishTask.value = task
// 默认版本号:把源文件名里的版本没法猜,就留空让后端按来源版本进位
publishForm.value = { version: '', update_strategy: 'optional', changelog: '', publish_now: false }
publishOpen.value = true
}
async function submitPublish() {
if (!publishTask.value)
return
publishing.value = true
try {
const res = await api.post<any>(`/dev/protect/tasks/${publishTask.value.id}/publish`, publishForm.value)
toast.success(t('admin.protect.published', { v: res?.version || '' }))
publishOpen.value = false
await loadTasks()
}
catch (e: any) {
toast.error(e.message || t('admin.protect.failed'))
}
finally {
publishing.value = false
}
}
async function removeTask(task: Task) {
if (task.status === 'running') {
toast.error(t('admin.protect.busy'))
@@ -481,6 +512,9 @@ onBeforeUnmount(() => {
>
{{ t('admin.protect.download') }}
</UiButton>
<UiButton size="sm" :disabled="task.status !== 'done'" @click="openPublish(task)">
{{ t('admin.protect.makeVersion') }}
</UiButton>
<UiButton size="sm" variant="ghost" @click="removeTask(task)">
<Trash2 class="h-4 w-4" />
</UiButton>
@@ -493,5 +527,68 @@ onBeforeUnmount(() => {
</UiCardContent>
</UiCard>
</div>
<!-- 生成版本弹窗 -->
<div
v-if="publishOpen"
class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
@click.self="publishOpen = false"
>
<div class="w-full max-w-md rounded-lg border border-border bg-card p-6 shadow-xl">
<h3 class="mb-1 text-lg font-semibold">
{{ t('admin.protect.makeVersion') }}
</h3>
<p class="mb-4 text-sm text-muted-foreground">
{{ t('admin.protect.makeVersionHint') }}
</p>
<div class="space-y-3">
<div>
<label class="mb-1 block text-sm font-medium">{{ t('admin.protect.versionLabel') }}</label>
<input
v-model="publishForm.version"
class="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
:placeholder="t('admin.protect.versionPlaceholder')"
>
</div>
<div>
<label class="mb-1 block text-sm font-medium">{{ t('admin.protect.strategy') }}</label>
<select
v-model="publishForm.update_strategy"
class="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
>
<option value="optional">
{{ t('admin.protect.strategyOptional') }}
</option>
<option value="forced">
{{ t('admin.protect.strategyForced') }}
</option>
</select>
</div>
<div>
<label class="mb-1 block text-sm font-medium">{{ t('admin.protect.changelog') }}</label>
<textarea
v-model="publishForm.changelog"
rows="3"
class="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
:placeholder="t('admin.protect.changelogPlaceholder')"
/>
</div>
<label class="flex items-center gap-2 text-sm">
<input v-model="publishForm.publish_now" type="checkbox" class="h-4 w-4">
{{ t('admin.protect.publishNow') }}
</label>
</div>
<div class="mt-5 flex justify-end gap-2">
<UiButton variant="ghost" :disabled="publishing" @click="publishOpen = false">
{{ t('admin.protect.cancel') }}
</UiButton>
<UiButton :disabled="publishing" @click="submitPublish">
{{ publishing ? t('admin.protect.working') : t('admin.protect.confirm') }}
</UiButton>
</div>
</div>
</div>
</BasicPage>
</template>
+15 -1
View File
@@ -2601,7 +2601,21 @@
"deleted": "Deleted",
"failed": "Operation failed",
"loadFailed": "Failed to load tasks",
"loadAppsFailed": "Failed to load applications"
"loadAppsFailed": "Failed to load applications",
"makeVersion": "Create version",
"makeVersionHint": "Write the protected artifact as a new version record: clients decide updates by increasing version-record id, so replacing an already-published file in place never propagates.",
"versionLabel": "Version",
"versionPlaceholder": "Leave empty to auto-bump the source version",
"strategy": "Update strategy",
"strategyOptional": "Optional",
"strategyForced": "Forced",
"changelog": "Changelog",
"changelogPlaceholder": "e.g. wrapped with verification shell",
"publishNow": "Publish immediately (otherwise kept as draft)",
"cancel": "Cancel",
"confirm": "OK",
"working": "Working…",
"published": "Version {v} created"
}
},
"auth": {
+15 -1
View File
@@ -2620,7 +2620,21 @@
"deleted": "已删除",
"failed": "操作失败",
"loadFailed": "加载任务失败",
"loadAppsFailed": "加载应用失败"
"loadAppsFailed": "加载应用失败",
"makeVersion": "生成版本",
"makeVersionHint": "把加壳产物写成一条新的版本记录:客户端按版本记录 ID 递增判定更新,原地换包推不下去。其余资源文件沿用来源版本。",
"versionLabel": "版本号",
"versionPlaceholder": "留空则按来源版本末段 +1",
"strategy": "更新策略",
"strategyOptional": "可选更新(optional)",
"strategyForced": "强制更新(forced)",
"changelog": "更新说明",
"changelogPlaceholder": "例如:接入验证壳,需登录后使用",
"publishNow": "创建后立即发布(否则存为草稿)",
"cancel": "取消",
"confirm": "确定",
"working": "处理中…",
"published": "已生成版本 {v}"
}
},
"auth": {