From 02df87f464572c6f786bc108310a028903dccb7c Mon Sep 17 00:00:00 2001 From: hermes Date: Sat, 21 Nov 2026 15:19:56 +0800 Subject: [PATCH] =?UTF-8?q?feat(protect):=20=E5=8A=A0=E5=A3=B3=E4=BA=A7?= =?UTF-8?q?=E7=89=A9=E8=90=BD=E6=88=90=E6=96=B0=E7=89=88=E6=9C=AC=E8=AE=B0?= =?UTF-8?q?=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- backend/internal/model/models.go | 4 + backend/internal/protect/publish.go | 200 +++++++++++++++++++++ backend/internal/protect/publish_test.go | 20 +++ backend/internal/protect/task.go | 9 + backend/internal/router/admin/protect.go | 49 +++++ backend/internal/router/mcp/mcp.go | 71 +++++++- frontend/src/pages/admin/protect/index.vue | 97 ++++++++++ frontend/src/plugins/i18n/en.json | 16 +- frontend/src/plugins/i18n/zh.json | 16 +- 9 files changed, 479 insertions(+), 3 deletions(-) create mode 100644 backend/internal/protect/publish.go create mode 100644 backend/internal/protect/publish_test.go diff --git a/backend/internal/model/models.go b/backend/internal/model/models.go index ddf41f5..e420dcb 100644 --- a/backend/internal/model/models.go +++ b/backend/internal/model/models.go @@ -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"` diff --git a/backend/internal/protect/publish.go b/backend/internal/protect/publish.go new file mode 100644 index 0000000..1ae022a --- /dev/null +++ b/backend/internal/protect/publish.go @@ -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" +} diff --git a/backend/internal/protect/publish_test.go b/backend/internal/protect/publish_test.go new file mode 100644 index 0000000..14648b2 --- /dev/null +++ b/backend/internal/protect/publish_test.go @@ -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) + } + } +} diff --git a/backend/internal/protect/task.go b/backend/internal/protect/task.go index d4053ce..2876cb3 100644 --- a/backend/internal/protect/task.go +++ b/backend/internal/protect/task.go @@ -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 diff --git a/backend/internal/router/admin/protect.go b/backend/internal/router/admin/protect.go index f810eb0..7b93091 100644 --- a/backend/internal/router/admin/protect.go +++ b/backend/internal/router/admin/protect.go @@ -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") diff --git a/backend/internal/router/mcp/mcp.go b/backend/internal/router/mcp/mcp.go index 3dd0bc8..a8c61bd 100644 --- a/backend/internal/router/mcp/mcp.go +++ b/backend/internal/router/mcp/mcp.go @@ -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, }) }) } diff --git a/frontend/src/pages/admin/protect/index.vue b/frontend/src/pages/admin/protect/index.vue index 302322c..378e4d9 100644 --- a/frontend/src/pages/admin/protect/index.vue +++ b/frontend/src/pages/admin/protect/index.vue @@ -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(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(`/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') }} + + {{ t('admin.protect.makeVersion') }} + @@ -493,5 +527,68 @@ onBeforeUnmount(() => { + + +
+
+

+ {{ t('admin.protect.makeVersion') }} +

+

+ {{ t('admin.protect.makeVersionHint') }} +

+ +
+
+ + +
+
+ + +
+
+ +