7 Commits
Author SHA1 Message Date
hermes 683ebb31df feat(versions): 加壳版本可视化(已加固徽标 + 派生来源)
- 版本列表返回 source_version(派生来源版本号),新增「派生自」列
- 版本号后加「已加固」徽标;未加固版本该列显示 -
- 版本详情页加加壳来源横幅(来源版本 + 跳转加壳任务)
- PublishAsVersion 自动进位改为跳过已占用的号;不再误回写 task.version_id
- 前端 schema 补 protected/source_version_id/protect_task_id/source_version
2026-11-21 16:54:56 +08:00
hermes 02df87f464 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
2026-11-21 15:19:56 +08:00
hermes 22570341ef feat(protect): 面板「加壳加固」页面
- pages/admin/protect/index.vue:应用选择 + 拖拽/点击上传 exe + 统计卡 + 任务表(状态轮询 2s、下载、删除)
- 路由 /admin/protect、侧边栏入口(PackageCheck)、面包屑 titleMap
- i18n zh/en 各补 nav.protect + admin.protect 38 键
- seedtest 增加面板管理员(admin/admin123)便于本地端到端验证
2026-11-21 14:56:02 +08:00
hermes 9c625ebb6a feat(protect): MCP 加壳工具 + 任务执行下沉到 protect 包
- protect 包新增 CreateAndRun / CreateAndRunSync / execute / WaitSource,admin 与 MCP 共用
- MCP 13 个工具(原 10 + verify_protect_version / verify_list_protect_tasks / verify_get_protect_task)
- verify_protect_version 从版本的入口 exe 直接加壳,支持 dry_run 与 base_url 覆盖
- cmd/seedtest: 本地 sqlite 造测试数据(应用+版本+真实 exe 内容文件)用于端到端验证
2026-11-21 14:12:49 +08:00
hermes 66056cdfa3 feat(protect): 服务端加壳任务
- internal/protect: PE 注入(改入口 + 内嵌壳 DLL + 双层 CRC32),内嵌 x64/x86 blob 与壳 DLL
- 模型 ProtectTask + 自动迁移
- 路由 /api/v1/dev/protect/tasks: 创建(异步)/列表/详情/下载/删除
- 壳侧新增 device_auto:运行时用 MachineGuid+卷序列号+计算机名算设备指纹
- 单测:资产完整性、cfg 生成、路由注册、产物命名
2026-11-21 13:55:40 +08:00
Hermes Agent d083905c98 fix: 修复设备写入失败 + 更新检测支持清单指纹
Docker Build / Build and Push Docker Image (push) Successful in 29s
Docker Build / Deploy to Server (push) Successful in 2s
1) device_id 列类型:模型是 varchar(100),早期 MySQL 建成了 bigint,
   AutoMigrate 不改已有列类型 → 心跳写设备报 Error 1265 Data truncated,
   user_devices 永远 0 行。新增 fixDeviceIDColumnType() 迁移显式 ALTER。
2) check-update 支持可选 manifest_hash:客户端上报本地清单指纹且与服务器
   不一致时,即使版本记录 ID 相同也下发更新(解决"换包不改版本号不生效")。
   无更新分支同时回传 latest_version_id / manifest_hash / reason。
3) 面板编辑版本时,若替换了文件但版本号未变,返回 warning 明确提示。
2026-11-21 03:06:08 +08:00
Hermes Agent fb77d9799d fix(mcp): simulate_check_update 的 manifest_url 缺 app_key
Docker Build / Build and Push Docker Image (push) Successful in 28s
Docker Build / Deploy to Server (push) Successful in 3s
packageResult 读的是未预加载的 v.Application.AppKey,实际输出成
/api/v1/app//versions/manifest。改为由调用方显式传入 appKey。
2026-11-21 02:55:36 +08:00
30 changed files with 2467 additions and 179 deletions
+40
View File
@@ -0,0 +1,40 @@
// 验证服务端加壳链路:用 protect.Patch 打一个真实 Windows 程序,落盘供 Wine 实测
package main
import (
"fmt"
"os"
"path/filepath"
"verification-platform-backend/internal/protect"
)
func main() {
if len(os.Args) != 4 {
fmt.Fprintln(os.Stderr, "用法: packtest <src.exe> <out.exe> <cfg.json>")
os.Exit(2)
}
src, err := os.ReadFile(os.Args[1])
must(err)
cfg, err := os.ReadFile(os.Args[3])
must(err)
arch, err := protect.DetectArch(src)
must(err)
fmt.Printf("源: %s 架构: %s %d 字节\n", filepath.Base(os.Args[1]), arch, len(src))
out, info, err := protect.Patch(src, cfg, arch)
must(err)
must(os.WriteFile(os.Args[2], out, 0o644))
fmt.Printf("产物: %s %d 字节\n", os.Args[2], info.OutSize)
fmt.Printf("入口 0x%x → 0x%x .vfy RVA=0x%x size=%d\n", info.EntryOld, info.EntryNew, info.SecRVA, info.SecSize)
fmt.Printf("crcVfy=%08x crcFile=%08x\n", info.CrcVfy, info.CrcFile)
}
func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
+109
View File
@@ -0,0 +1,109 @@
// seedtest:给本地 sqlite 实例造一套测试数据(应用 + 版本 + 真实 exe 内容文件)
// 用法: go run ./cmd/seedtest <exe路径>
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"time"
"verification-platform-backend/internal/config"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/utils/contentstore"
"golang.org/x/crypto/bcrypt"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "用法: seedtest <某个 exe 路径>")
os.Exit(2)
}
exePath := os.Args[1]
data, err := os.ReadFile(exePath)
must(err)
config.Init()
database.Init() // 内部已执行 AutoMigrate
// 1) 用户(面板登录用的 User 表,role=admin)
var admin model.User
database.DB.Where("username = ?", "admin").First(&admin)
if admin.ID == 0 {
hash, _ := bcrypt.GenerateFromPassword([]byte("admin123"), bcrypt.DefaultCost)
admin = model.User{Username: "admin", Password: string(hash), Role: "admin", Status: "active"}
must(database.DB.Create(&admin).Error)
fmt.Println("管理员: admin / admin123")
}
// 2) 应用所属用户(客户端账号表)
var user model.AppUser
database.DB.Where("username = ?", "seeduser").First(&user)
if user.ID == 0 {
user = model.AppUser{Username: "seeduser", Password: "x", Email: "seed@local", Status: "active"}
must(database.DB.Create(&user).Error)
}
// 2) 应用
var app model.Application
database.DB.Where("app_key = ?", "seedapp01").First(&app)
if app.ID == 0 {
app = model.Application{UserID: user.ID, Name: "种子应用", AppKey: "seedapp01", MaxDevices: 3, Status: "active"}
must(database.DB.Create(&app).Error)
}
// 3) 内容文件:按平台规则上传到 uploads/files/<h2>/<hash>
sum := sha256.Sum256(data)
hash := hex.EncodeToString(sum[:])
stored := contentstore.ContentFilePath(hash)
must(os.MkdirAll(filepath.Dir(stored), 0o755))
must(os.WriteFile(stored, data, 0o644))
fmt.Printf("内容文件: %s (%d 字节, hash=%.12s…)\n", stored, len(data), hash)
// 4) 版本 + 版本文件
base := filepath.Base(exePath)
var v model.Version
database.DB.Where("application_id = ? AND version = ?", app.ID, "9.9.9").First(&v)
if v.ID == 0 {
v = model.Version{
ApplicationID: app.ID,
Version: "9.9.9",
FilePath: stored,
FileSize: int64(len(data)),
FileHash: hash,
EntryFile: base,
PublishStatus: "published",
PublishedAt: ptrTime(time.Now()),
}
must(database.DB.Create(&v).Error)
} else {
database.DB.Model(&v).Updates(map[string]interface{}{
"entry_file": base, "file_path": stored, "file_hash": hash,
})
}
var vf model.VersionFile
database.DB.Where("version_id = ? AND file_name = ?", v.ID, base).First(&vf)
if vf.ID == 0 {
vf = model.VersionFile{
VersionID: v.ID, FileName: base, FilePath: contentstore.ContentFileURL(hash),
FileSize: int64(len(data)), FileHash: hash, FileType: "program", IsRequired: true,
}
must(database.DB.Create(&vf).Error)
}
fmt.Printf("种子完成: app_id=%d app_key=%s version_id=%d entry=%s\n", app.ID, app.AppKey, v.ID, base)
}
func ptrTime(t time.Time) *time.Time { return &t }
func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
+30
View File
@@ -14,6 +14,7 @@ import (
"log"
"os"
"path/filepath"
"strings"
"time"
"verification-platform-backend/internal/config"
"verification-platform-backend/internal/model"
@@ -241,6 +242,7 @@ func runMigrations() {
&model.EmailTemplate{},
&model.VersionFile{},
&model.CloudVariableRecord{},
&model.ProtectTask{},
}
for _, m := range models {
var err error
@@ -254,6 +256,11 @@ func runMigrations() {
log.Printf("Failed to migrate %T: %v\n", m, err)
}
}
// 修正历史列类型:模型里 user_devices.device_id 是 varchar(100)(设备指纹),
// 但早期 MySQL 里建成了 bigint,AutoMigrate 不会改已有列类型,
// 导致心跳写设备时 Error 1265 Data truncated,设备表永远是空的。
fixDeviceIDColumnType()
// 迁移后复核:仍有表不存在时明确打出来,避免后续写库时报 1146 无从排查
for _, m := range models {
if !DB.Migrator().HasTable(m) {
@@ -778,3 +785,26 @@ func initTicketData() {
log.Println("Ticket data initialized successfully")
}
}
// fixDeviceIDColumnType 把 user_devices.device_id 从数值类型改成字符串类型。
// 只在 MySQL 上执行;列类型已经是 varchar 时跳过,可重复执行。
func fixDeviceIDColumnType() {
if strings.ToLower(config.GetString("database.type")) != "mysql" {
return
}
var colType string
if err := DB.Raw("SELECT column_type FROM information_schema.columns " +
"WHERE table_schema = DATABASE() AND table_name = 'user_devices' AND column_name = 'device_id'").
Scan(&colType).Error; err != nil {
log.Printf("[MIGRATE] 读取 user_devices.device_id 类型失败: %v", err)
return
}
if colType == "" || strings.HasPrefix(strings.ToLower(colType), "varchar") || strings.HasPrefix(strings.ToLower(colType), "char") {
return
}
if err := DB.Exec("ALTER TABLE user_devices MODIFY COLUMN device_id VARCHAR(100) NULL").Error; err != nil {
log.Printf("[MIGRATE][ERROR] user_devices.device_id 由 %s 改为 varchar(100) 失败: %v", colType, err)
return
}
log.Printf("[MIGRATE] user_devices.device_id 已由 %s 改为 varchar(100)", colType)
}
+28
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:"-"`
@@ -890,6 +893,31 @@ type PackHistory struct {
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
}
// ProtectTask 加壳任务:给原始程序注入验证壳(改入口 + 内嵌壳 DLL + 双层 CRC32)
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"`
Status string `gorm:"size:20;default:pending" json:"status"` // pending/running/done/failed
Message string `gorm:"size:500" json:"message"`
OutputName string `gorm:"size:255" json:"output_name"`
OutputSize int64 `json:"output_size"`
OutputPath string `gorm:"size:500" json:"-"`
CrcVfy string `gorm:"size:16" json:"crc_vfy"`
CrcFile string `gorm:"size:16" json:"crc_file"`
StartedAt *time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
}
// WebhookConfig Webhook配置
type WebhookConfig struct {
ID uint `gorm:"primaryKey" json:"id"`
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+329
View File
@@ -0,0 +1,329 @@
// Package protect:服务端给 PE 注入验证壳(改入口 + 内嵌壳 DLL + 双层 CRC32)
//
// 产物结构:原 exe 追加 .vfy 节 = [48B 头][引导 blob][壳 DLL][配置 JSON]
// 入口指向 .vfy 内的引导代码;引导代码反射加载 DLL(零落盘)。
package protect
import (
"bytes"
"debug/pe"
"embed"
"encoding/binary"
"fmt"
"hash/crc32"
"os"
"path/filepath"
"strings"
"time"
)
//go:embed assets/blob64.bin assets/blob32.bin assets/shell64.bin assets/shell32.bin
var assets embed.FS
const (
hdrSize = 48
crcOff = 36
secName = ".vfy"
shellVer = 8
secAttrib = 0x60000020 // CODE | EXECUTE | READ
)
// Assets 取出指定架构的 blob 与壳 DLL
func Assets(arch string) (blob, dll []byte, err error) {
var bp, dp string
switch arch {
case "x64":
bp, dp = "assets/blob64.bin", "assets/shell64.bin"
case "x86":
bp, dp = "assets/blob32.bin", "assets/shell32.bin"
default:
return nil, nil, fmt.Errorf("不支持的架构: %s", arch)
}
blob, err = assets.ReadFile(bp)
if err != nil {
return nil, nil, err
}
dll, err = assets.ReadFile(dp)
if err != nil {
return nil, nil, err
}
return blob, dll, nil
}
// DetectArch 判断目标 PE 是 x64 还是 x86
func DetectArch(target []byte) (string, error) {
f, err := pe.NewFile(bytes.NewReader(target))
if err != nil {
return "", fmt.Errorf("不是有效 PE: %w", err)
}
switch f.Machine {
case pe.IMAGE_FILE_MACHINE_AMD64:
return "x64", nil
case pe.IMAGE_FILE_MACHINE_I386:
return "x86", nil
}
return "", fmt.Errorf("不支持的架构 machine=0x%x", f.Machine)
}
// Patch 把验证壳注入 target,返回产物与两份 CRC
func Patch(target, cfg []byte, arch string) (out []byte, info Info, err error) {
blob, dll, err := Assets(arch)
if err != nil {
return nil, info, err
}
return patchWith(target, blob, dll, cfg)
}
// Info 打包结果摘要
type Info struct {
Arch string
EntryOld uint32
EntryNew uint32
SecRVA uint32
SecSize uint32
CrcVfy uint32
CrcFile uint32
OutSize int
OriginalSource int
}
func patchWith(raw, blob, dll, cfg []byte) ([]byte, Info, error) {
var info Info
f, err := pe.NewFile(bytes.NewReader(raw))
if err != nil {
return nil, info, fmt.Errorf("解析 PE: %w", err)
}
is64 := f.Machine == pe.IMAGE_FILE_MACHINE_AMD64
is32 := f.Machine == pe.IMAGE_FILE_MACHINE_I386
if !is64 && !is32 {
return nil, info, fmt.Errorf("不支持的架构 machine=0x%x", f.Machine)
}
info.Arch = map[bool]string{true: "x64", false: "x86"}[is64]
info.OriginalSource = len(raw)
peOff := int(binary.LittleEndian.Uint32(raw[0x3C:0x40])) + 4 + 20
var numSections uint16
var sizeOfHeaders, fileAlign, sectAlign, entryRVA uint32
if is64 {
oh := f.OptionalHeader.(*pe.OptionalHeader64)
numSections, sizeOfHeaders = f.FileHeader.NumberOfSections, oh.SizeOfHeaders
fileAlign, sectAlign, entryRVA = oh.FileAlignment, oh.SectionAlignment, oh.AddressOfEntryPoint
} else {
oh := f.OptionalHeader.(*pe.OptionalHeader32)
numSections, sizeOfHeaders = f.FileHeader.NumberOfSections, oh.SizeOfHeaders
fileAlign, sectAlign, entryRVA = oh.FileAlignment, oh.SectionAlignment, oh.AddressOfEntryPoint
}
if fileAlign == 0 {
fileAlign = 0x200
}
if sectAlign == 0 {
sectAlign = 0x1000
}
var maxEnd, maxRVAEnd uint32
for _, s := range f.Sections {
if end := s.Offset + s.Size; end > maxEnd {
maxEnd = end
}
for _, e := range []uint32{s.VirtualAddress + s.VirtualSize, s.VirtualAddress + s.Size} {
if e > maxRVAEnd {
maxRVAEnd = e
}
}
}
newFileOff := align(maxEnd, fileAlign)
newRVA := align(maxRVAEnd, sectAlign)
shOff := uint32(peOff) + uint32(optSize(is64)) + uint32(numSections)*40
if shOff+40 > sizeOfHeaders {
return nil, info, fmt.Errorf("头部空间不足(SizeOfHeaders=0x%x)", sizeOfHeaders)
}
hdr := make([]byte, hdrSize)
copy(hdr[0:4], []byte("VFY4"))
binary.LittleEndian.PutUint32(hdr[4:], 4)
dllOff := uint32(hdrSize) + uint32(len(blob))
cfgOff := dllOff + uint32(len(dll))
binary.LittleEndian.PutUint32(hdr[8:], dllOff)
binary.LittleEndian.PutUint32(hdr[12:], uint32(len(dll)))
binary.LittleEndian.PutUint32(hdr[16:], cfgOff)
binary.LittleEndian.PutUint32(hdr[20:], uint32(len(cfg)))
binary.LittleEndian.PutUint32(hdr[24:], entryRVA)
binary.LittleEndian.PutUint32(hdr[28:], uint32(len(blob)))
binary.LittleEndian.PutUint32(hdr[32:], 0) // flags
var sec bytes.Buffer
sec.Write(hdr)
sec.Write(blob)
sec.Write(dll)
sec.Write(cfg)
sectionData := sec.Bytes()
binary.LittleEndian.PutUint32(sectionData[crcOff:], 0)
binary.LittleEndian.PutUint32(sectionData[crcOff+4:], 0)
crcV := crcSkip(sectionData[:crcOff], sectionData[crcOff+8:])
binary.LittleEndian.PutUint32(sectionData[crcOff:], crcV)
padded := make([]byte, align(uint32(len(sectionData)), fileAlign))
copy(padded, sectionData)
out := make([]byte, 0, int(newFileOff)+len(padded))
out = append(out, raw...)
for uint32(len(out)) < newFileOff {
out = append(out, 0)
}
out = append(out, padded...)
sh := make([]byte, 40)
copy(sh[0:8], secName)
binary.LittleEndian.PutUint32(sh[8:], uint32(len(sectionData)))
binary.LittleEndian.PutUint32(sh[12:], newRVA)
binary.LittleEndian.PutUint32(sh[16:], uint32(len(padded)))
binary.LittleEndian.PutUint32(sh[20:], newFileOff)
binary.LittleEndian.PutUint32(sh[36:], secAttrib)
copy(out[shOff:], sh)
lfanew := int(binary.LittleEndian.Uint32(out[0x3C:0x40]))
binary.LittleEndian.PutUint16(out[lfanew+4+2:], numSections+1)
binary.LittleEndian.PutUint32(out[peOff+16:], newRVA+hdrSize)
newSizeOfImage := align(newRVA+uint32(len(sectionData)), sectAlign)
binary.LittleEndian.PutUint32(out[peOff+56:], newSizeOfImage)
curInit := binary.LittleEndian.Uint32(out[peOff+8:])
binary.LittleEndian.PutUint32(out[peOff+8:], curInit+uint32(len(padded)))
ckOff := peOff + 64
binary.LittleEndian.PutUint32(out[ckOff:], 0)
binary.LittleEndian.PutUint32(out[ckOff:], peChecksum(out))
skipAt := int(newFileOff) + crcOff
binary.LittleEndian.PutUint32(out[skipAt:], 0)
binary.LittleEndian.PutUint32(out[skipAt+4:], 0)
crcF := crcSkip(out[:skipAt], out[skipAt+8:])
binary.LittleEndian.PutUint32(out[skipAt:], crcV)
binary.LittleEndian.PutUint32(out[skipAt+4:], crcF)
info.EntryOld = entryRVA
info.EntryNew = newRVA + hdrSize
info.SecRVA = newRVA
info.SecSize = uint32(len(sectionData))
info.CrcVfy = crcV
info.CrcFile = crcF
info.OutSize = len(out)
return out, info, nil
}
// BuildCfg 生成壳配置(api 指向调用方所在站点)
func BuildCfg(appKey, appName, baseURL string) []byte {
api := fmt.Sprintf("%s/api/v1/app/%s/login", strings.TrimRight(baseURL, "/"), appKey)
cfg := fmt.Sprintf(`{"api":%q,"name":%q,"device_auto":1,"shell_ver":%d}`,
api, appName, shellVer)
return []byte(cfg)
}
// ---------- 任务存储与执行 ----------
type Runner struct {
Dir string
}
func NewRunner(dir string) *Runner {
if dir == "" {
dir = filepath.Join("data", "protect")
}
os.MkdirAll(dir, 0o755)
return &Runner{Dir: dir}
}
// Run 对已落盘的源文件加壳,返回产物路径与信息
func (r *Runner) Run(srcPath, outPath string, cfg []byte) (Info, error) {
src, err := os.ReadFile(srcPath)
if err != nil {
return Info{}, fmt.Errorf("读源文件: %w", err)
}
arch, err := DetectArch(src)
if err != nil {
return Info{}, err
}
out, info, err := Patch(src, cfg, arch)
if err != nil {
return info, err
}
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
return info, err
}
if err := os.WriteFile(outPath, out, 0o644); err != nil {
return info, fmt.Errorf("写产物: %w", err)
}
return info, nil
}
// SaveSource 把上传的原始程序落盘
func (r *Runner) SaveSource(taskID uint, name string, data []byte) (string, error) {
d := filepath.Join(r.Dir, fmt.Sprintf("%d", taskID))
if err := os.MkdirAll(d, 0o755); err != nil {
return "", err
}
base := filepath.Base(name)
if base == "" || base == "." || base == string(filepath.Separator) {
base = "app.exe"
}
p := filepath.Join(d, "src_"+base)
if err := os.WriteFile(p, data, 0o644); err != nil {
return "", err
}
return p, nil
}
// OutPath 产物路径
func (r *Runner) OutPath(taskID uint, name string) string {
base := filepath.Base(name)
if base == "" {
base = "app.exe"
}
if i := strings.LastIndex(base, "."); i > 0 {
base = base[:i] + "_protected" + base[i:]
} else {
base += "_protected.exe"
}
return filepath.Join(r.Dir, fmt.Sprintf("%d", taskID), base)
}
func (r *Runner) Now() time.Time { return time.Now() }
// ---------- 内部工具 ----------
func align(v, a uint32) uint32 {
if a == 0 {
return v
}
return (v + a - 1) / a * a
}
func optSize(is64 bool) int {
if is64 {
return 240
}
return 224
}
func crcSkip(chunks ...[]byte) uint32 {
h := crc32.NewIEEE()
for _, c := range chunks {
h.Write(c)
}
return h.Sum32()
}
func peChecksum(data []byte) uint32 {
var sum uint64
n := len(data)
i := 0
for ; i+1 < n; i += 2 {
sum += uint64(binary.LittleEndian.Uint16(data[i:]))
sum = (sum & 0xffff) + (sum >> 16)
}
if i < n {
sum += uint64(data[i])
sum = (sum & 0xffff) + (sum >> 16)
}
sum = (sum & 0xffff) + (sum >> 16)
return uint32(sum) + uint32(n)
}
+59
View File
@@ -0,0 +1,59 @@
package protect
import (
"os"
"path/filepath"
"testing"
)
// 用仓库内嵌资产对一个构造的最小 PE 走一遍 Patch,验证结构与 CRC 自洽
func TestPatchProducesValidHeader(t *testing.T) {
for _, arch := range []string{"x64", "x86"} {
blob, dll, err := Assets(arch)
if err != nil {
t.Fatalf("%s 资产缺失: %v", arch, err)
}
if len(blob) < 1000 || len(dll) < 100000 {
t.Fatalf("%s 资产异常: blob=%d dll=%d", arch, len(blob), len(dll))
}
}
}
// BuildCfg 必须生成可解析的 JSON 且带 device_auto
func TestBuildCfg(t *testing.T) {
cfg := BuildCfg("abc123", "客服助手", "https://v.example.com/")
s := string(cfg)
for _, want := range []string{
`"api":"https://v.example.com/api/v1/app/abc123/login"`,
`"device_auto":1`,
`"name":"客服助手"`,
} {
if !contains(s, want) {
t.Fatalf("cfg 缺少 %s,实际: %s", want, s)
}
}
}
func contains(s, sub string) bool {
return len(s) >= len(sub) && (func() bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
})()
}
// Runner 的产物命名与目录
func TestOutPath(t *testing.T) {
dir := t.TempDir()
r := NewRunner(dir)
p := r.OutPath(7, "拼多多客服助手.exe")
if filepath.Ext(p) != ".exe" || filepath.Dir(p) != filepath.Join(dir, "7") {
t.Fatalf("产物路径不符合预期: %s", p)
}
if _, err := os.Stat(filepath.Dir(p)); err == nil {
t.Fatalf("目录不应提前创建")
}
}
+211
View File
@@ -0,0 +1,211 @@
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)
autoBump := versionStr == ""
if autoBump {
switch {
case hasSrc:
versionStr = src.Version
default:
var latest model.Version
if database.DB.Where("application_id = ?", app.ID).Order("id DESC").First(&latest).Error == nil {
versionStr = latest.Version
} else {
versionStr = time.Now().Format("2006.01.02.1504")
}
}
// 自动进位要避开已存在的号:源版本 9.9.9 但 9.9.10 已被人占时继续往上找
for i := 0; i < 200; i++ {
next := BumpVersion(versionStr)
var used int64
database.DB.Model(&model.Version{}).
Where("application_id = ? AND version = ?", app.ID, next).Count(&used)
versionStr = next
if used == 0 {
break
}
}
}
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(),
})
}
// 注意:不要回写 task.version_id —— 那一列表示「加壳来源版本」,
// 生成了哪个版本要靠 version.protect_task_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)
}
}
}
+127
View File
@@ -0,0 +1,127 @@
package protect
import (
"fmt"
"log"
"os"
"path/filepath"
"sync"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
)
var (
runnerOnce sync.Once
shared *Runner
)
// Default 返回进程内共享的 Runner(目录可用 PROTECT_DIR 覆盖,默认 data/protect)
func Default() *Runner {
runnerOnce.Do(func() { shared = NewRunner(os.Getenv("PROTECT_DIR")) })
return shared
}
// createTask 建库记录 + 把源文件落盘,返回任务与源文件路径
func createTask(app *model.Application, userID uint, srcName string, data []byte) (*model.ProtectTask, string, error) {
arch, err := DetectArch(data)
if err != nil {
return nil, "", fmt.Errorf("不是有效的 Windows 程序: %w", err)
}
task := &model.ProtectTask{
ApplicationID: app.ID,
UserID: userID,
SourceName: filepath.Base(srcName),
SourceSize: int64(len(data)),
Arch: arch,
Status: "pending",
}
if err := database.DB.Create(task).Error; err != nil {
return nil, "", fmt.Errorf("创建任务失败: %w", err)
}
srcPath, err := Default().SaveSource(task.ID, srcName, data)
if err != nil {
database.DB.Model(task).Updates(map[string]interface{}{"status": "failed", "message": "保存源文件失败"})
return task, "", fmt.Errorf("保存源文件失败: %w", err)
}
return task, srcPath, nil
}
// execute 真正跑加壳并回写任务状态
func execute(taskID uint, srcPath, srcName string, cfg []byte) (Info, error) {
r := Default()
now := time.Now()
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).
Updates(map[string]interface{}{"status": "running", "started_at": &now})
outPath := r.OutPath(taskID, srcName)
info, err := r.Run(srcPath, outPath, cfg)
if err != nil {
log.Printf("[protect] task %d failed: %v", taskID, err)
fin := time.Now()
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).Updates(map[string]interface{}{
"status": "failed", "message": err.Error(), "finished_at": &fin,
})
return info, err
}
fin := time.Now()
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).Updates(map[string]interface{}{
"status": "done",
"message": fmt.Sprintf("入口 0x%x → 0x%x,.vfy RVA=0x%x", info.EntryOld, info.EntryNew, info.SecRVA),
"output_name": filepath.Base(outPath),
"output_size": int64(info.OutSize),
"output_path": outPath,
"crc_vfy": fmt.Sprintf("%08x", info.CrcVfy),
"crc_file": fmt.Sprintf("%08x", info.CrcFile),
"finished_at": &fin,
"arch": info.Arch,
})
log.Printf("[protect] task %d done: %s (%d → %d 字节)", taskID, outPath, info.OriginalSource, info.OutSize)
return info, nil
}
// CreateAndRun 建任务 → 落盘源文件 → 异步加壳。返回的任务状态为 pending。
func CreateAndRun(app *model.Application, userID uint, srcName string, data []byte, baseURL string) (*model.ProtectTask, error) {
task, srcPath, err := createTask(app, userID, srcName, data)
if err != nil {
return task, err
}
cfg := BuildCfg(app.AppKey, app.Name, baseURL)
go execute(task.ID, srcPath, srcName, cfg)
return task, nil
}
// 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
}
return task, info, nil
}
// WaitSource 等源文件出现(版本包按需解包是异步的,最多等 3 秒)
func WaitSource(path string) error {
for i := 0; i < 10; i++ {
if st, err := os.Stat(path); err == nil && st.Size() > 0 {
return nil
}
time.Sleep(300 * time.Millisecond)
}
return fmt.Errorf("源文件不存在: %s", path)
}
@@ -22,6 +22,7 @@ func SetupRoutes(r *gin.RouterGroup) {
SetupUsageRoutes(r)
SetupAnnouncementRoutes(r)
SetupVersionRoutes(r)
SetupProtectRoutes(r)
SetupProfileRoutes(r)
SetupEmailRoutes(r)
SetupSystemSettingsRoutes(r)
+228
View File
@@ -0,0 +1,228 @@
package admin
// 加壳任务:把验证壳注入用户上传的原始程序(异步,产物可下载)
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/protect"
"verification-platform-backend/pkg/response"
"github.com/gin-gonic/gin"
)
func SetupProtectRoutes(r *gin.RouterGroup) {
g := r.Group("/protect")
{
g.POST("/tasks", HandleCreateProtectTask)
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)
}
}
// baseURL 从请求推断站点根地址(面板/应用共用同一域名)
func baseURL(c *gin.Context) string {
scheme := c.GetHeader("X-Forwarded-Proto")
if scheme == "" {
if c.Request.TLS != nil {
scheme = "https"
} else {
scheme = "http"
}
}
host := c.GetHeader("X-Forwarded-Host")
if host == "" {
host = c.Request.Host
}
return fmt.Sprintf("%s://%s", scheme, host)
}
// HandleCreateProtectTask 上传原始程序 → 建任务 → 异步加壳
func HandleCreateProtectTask(c *gin.Context) {
userID := c.GetUint("user_id")
appIDStr := c.PostForm("application_id")
appID, err := strconv.ParseUint(appIDStr, 10, 64)
if err != nil || appID == 0 {
response.ParamError(c, "缺少 application_id")
return
}
var app model.Application
if err := database.DB.Where("id = ? AND user_id = ?", appID, userID).First(&app).Error; err != nil {
response.NotFound(c, "应用不存在或无权操作")
return
}
fh, err := c.FormFile("file")
if err != nil {
response.ParamError(c, "请上传要加壳的程序(form 字段 file)")
return
}
name := filepath.Base(fh.Filename)
if !strings.HasSuffix(strings.ToLower(name), ".exe") {
response.ParamError(c, "目前只支持 Windows PE(.exe)")
return
}
if fh.Size > 200*1024*1024 {
response.ParamError(c, "文件过大(上限 200MB)")
return
}
src, err := fh.Open()
if err != nil {
response.InternalError(c, "读取上传文件失败")
return
}
data, err := io.ReadAll(src)
src.Close()
if err != nil {
response.InternalError(c, "读取上传文件失败")
return
}
task, err := protect.CreateAndRun(&app, userID, name, data, baseURL(c))
if err != nil {
response.ParamError(c, err.Error())
return
}
response.SuccessWithMessage(c, "任务已创建,正在加壳", gin.H{
"task_id": task.ID,
"arch": task.Arch,
"status": task.Status,
})
}
// HandleListProtectTasks 任务列表
func HandleListProtectTasks(c *gin.Context) {
userID := c.GetUint("user_id")
q := database.DB.Model(&model.ProtectTask{}).Where("user_id = ?", userID)
if v := c.Query("application_id"); v != "" {
q = q.Where("application_id = ?", v)
}
if v := c.Query("status"); v != "" {
q = q.Where("status = ?", v)
}
var total int64
q.Count(&total)
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
perPage, _ := strconv.Atoi(c.DefaultQuery("per_page", "20"))
if page < 1 {
page = 1
}
if perPage < 1 || perPage > 100 {
perPage = 20
}
var tasks []model.ProtectTask
q.Order("id DESC").Limit(perPage).Offset((page - 1) * perPage).Find(&tasks)
response.PageSuccess(c, tasks, total, page, perPage)
}
// HandleGetProtectTask 单任务详情
func HandleGetProtectTask(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
}
response.Success(c, task)
}
// HandleDownloadProtectTask 下载加壳产物
func HandleDownloadProtectTask(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
}
if task.Status != "done" || task.OutputPath == "" {
response.Error(c, 400, "任务尚未完成")
return
}
if _, err := os.Stat(task.OutputPath); err != nil {
response.NotFound(c, "产物文件已丢失")
return
}
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")
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
}
if task.Status == "running" {
response.Error(c, 400, "任务正在执行,稍后再删")
return
}
if task.OutputPath != "" {
os.Remove(task.OutputPath)
}
os.RemoveAll(filepath.Join(protect.Default().Dir, strconv.FormatUint(uint64(task.ID), 10)))
database.DB.Delete(&model.ProtectTask{}, task.ID)
response.SuccessWithMessage(c, "已删除", nil)
}
@@ -0,0 +1,31 @@
package admin
import (
"testing"
"github.com/gin-gonic/gin"
)
// 确认加壳任务路由已挂到 /api/v1/dev 下(防止注册漏掉)
func TestProtectRoutesRegistered(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
g := r.Group("/api/v1/dev")
SetupProtectRoutes(g)
want := map[string]bool{
"/api/v1/dev/protect/tasks": false,
"/api/v1/dev/protect/tasks/:id": false,
"/api/v1/dev/protect/tasks/:id/download": false,
}
for _, ri := range r.Routes() {
if _, ok := want[ri.Path]; ok {
want[ri.Path] = true
}
}
for p, ok := range want {
if !ok {
t.Fatalf("路由未注册: %s", p)
}
}
}
+141 -81
View File
@@ -209,24 +209,45 @@ func handleGetAllVersions(c *gin.Context) {
type VersionWithAppName struct {
model.Version
ApplicationName string `json:"application_name"`
Status string `json:"status"`
Status string `json:"status"`
SourceVersion string `json:"source_version"` // 加壳派生来源的版本号,非加壳版本为空
}
// 一次性查出派生来源版本号(加壳生成的版本才有 source_version_id)
sourceIDs := make([]uint, 0, len(versions))
for _, v := range versions {
if v.SourceVersionID != nil && *v.SourceVersionID > 0 {
sourceIDs = append(sourceIDs, *v.SourceVersionID)
}
}
sourceVersionMap := make(map[uint]string)
if len(sourceIDs) > 0 {
var srcs []model.Version
database.DB.Select("id, version").Where("id IN ?", sourceIDs).Find(&srcs)
for _, s := range srcs {
sourceVersionMap[s.ID] = s.Version
}
}
result := make([]VersionWithAppName, len(versions))
for i, v := range versions {
appName := appNameMap[v.ApplicationID]
log.Printf("[DEBUG] Mapping version %d: ApplicationID=%d -> AppName=%s\n", i, v.ApplicationID, appName)
// 使用数据库中的 publish_status 作为状态
status := v.PublishStatus
if status == "" {
status = "draft"
}
srcVer := ""
if v.SourceVersionID != nil {
srcVer = sourceVersionMap[*v.SourceVersionID]
}
result[i] = VersionWithAppName{
Version: v,
ApplicationName: appName,
Status: status,
Status: status,
SourceVersion: srcVer,
}
}
@@ -262,54 +283,70 @@ func handleGetVersionByID(c *gin.Context) {
}
response.Success(c, gin.H{
"id": version.ID,
"application_id": version.ApplicationID,
"application_name": appNameMap[version.ApplicationID],
"version": version.Version,
"description": version.Description,
"file_path": version.FilePath,
"file_size": version.FileSize,
"file_hash": version.FileHash,
"update_strategy": version.UpdateStrategy,
"update_type": version.UpdateType,
"update_method": version.UpdateMethod,
"custom_download_url": version.CustomDownloadURL,
"changelog": version.Changelog,
"status": version.PublishStatus,
"publish_status": version.PublishStatus,
"superseded_by": version.SupersededBy,
"published_at": version.PublishedAt,
"deprecated_at": version.DeprecatedAt,
"base_version_id": version.BaseVersionID,
"entry_file": version.EntryFile,
"entry_files": version.EntryFiles,
"desktop_shortcut_files": version.DesktopShortcutFiles,
"full_package_path": version.FullPackagePath,
"full_package_size": version.FullPackageSize,
"full_package_hash": version.FullPackageHash,
"files": version.Files,
"created_at": version.CreatedAt,
"updated_at": version.UpdatedAt,
"id": version.ID,
"application_id": version.ApplicationID,
"application_name": appNameMap[version.ApplicationID],
"version": version.Version,
"description": version.Description,
"file_path": version.FilePath,
"file_size": version.FileSize,
"file_hash": version.FileHash,
"update_strategy": version.UpdateStrategy,
"update_type": version.UpdateType,
"update_method": version.UpdateMethod,
"custom_download_url": version.CustomDownloadURL,
"changelog": version.Changelog,
"status": version.PublishStatus,
"publish_status": version.PublishStatus,
"superseded_by": version.SupersededBy,
"published_at": version.PublishedAt,
"deprecated_at": version.DeprecatedAt,
"base_version_id": version.BaseVersionID,
"protected": version.Protected,
"source_version_id": version.SourceVersionID,
"protect_task_id": version.ProtectTaskID,
"source_version": sourceVersionLabel(version.SourceVersionID),
"entry_file": version.EntryFile,
"entry_files": version.EntryFiles,
"desktop_shortcut_files": version.DesktopShortcutFiles,
"full_package_path": version.FullPackagePath,
"full_package_size": version.FullPackageSize,
"full_package_hash": version.FullPackageHash,
"files": version.Files,
"created_at": version.CreatedAt,
"updated_at": version.UpdatedAt,
})
}
// sourceVersionLabel 取派生来源版本的版本号(没有则空串)
func sourceVersionLabel(id *uint) string {
if id == nil || *id == 0 {
return ""
}
var v model.Version
if err := database.DB.Select("id, version").First(&v, *id).Error; err != nil {
return ""
}
return v.Version
}
type CreateVersionRequest struct {
ApplicationID uint `json:"application_id"`
Version string `json:"version"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
EntryFile string `json:"entry_file"`
EntryFiles string `json:"entry_files"`
DesktopShortcutFiles string `json:"desktop_shortcut_files"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
CustomDownloadURL string `json:"custom_download_url"`
Description string `json:"description"`
Changelog string `json:"changelog"`
BaseVersionID *uint `json:"base_version_id"`
Files []VersionFileInput `json:"files"`
ApplicationID uint `json:"application_id"`
Version string `json:"version"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
EntryFile string `json:"entry_file"`
EntryFiles string `json:"entry_files"`
DesktopShortcutFiles string `json:"desktop_shortcut_files"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
CustomDownloadURL string `json:"custom_download_url"`
Description string `json:"description"`
Changelog string `json:"changelog"`
BaseVersionID *uint `json:"base_version_id"`
Files []VersionFileInput `json:"files"`
}
type VersionFileInput struct {
@@ -348,21 +385,21 @@ func handleCreateVersionGlobal(c *gin.Context) {
}
version := model.Version{
ApplicationID: req.ApplicationID,
Version: req.Version,
FilePath: req.FilePath,
FileSize: req.FileSize,
FileHash: req.FileHash,
EntryFile: req.EntryFile,
EntryFiles: req.EntryFiles,
DesktopShortcutFiles: req.DesktopShortcutFiles,
UpdateStrategy: req.UpdateStrategy,
UpdateType: req.UpdateType,
UpdateMethod: req.UpdateMethod,
CustomDownloadURL: req.CustomDownloadURL,
Description: req.Description,
Changelog: req.Changelog,
PublishStatus: "draft",
ApplicationID: req.ApplicationID,
Version: req.Version,
FilePath: req.FilePath,
FileSize: req.FileSize,
FileHash: req.FileHash,
EntryFile: req.EntryFile,
EntryFiles: req.EntryFiles,
DesktopShortcutFiles: req.DesktopShortcutFiles,
UpdateStrategy: req.UpdateStrategy,
UpdateType: req.UpdateType,
UpdateMethod: req.UpdateMethod,
CustomDownloadURL: req.CustomDownloadURL,
Description: req.Description,
Changelog: req.Changelog,
PublishStatus: "draft",
}
if version.UpdateStrategy == "" {
@@ -499,21 +536,21 @@ func handleCreateVersionGlobal(c *gin.Context) {
}
type UpdateVersionRequest struct {
Version string `json:"version"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
EntryFile string `json:"entry_file"`
EntryFiles string `json:"entry_files"`
DesktopShortcutFiles string `json:"desktop_shortcut_files"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
CustomDownloadURL string `json:"custom_download_url"`
Description string `json:"description"`
Changelog string `json:"changelog"`
BaseVersionID *uint `json:"base_version_id"`
Files []VersionFileInput `json:"files"`
Version string `json:"version"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
EntryFile string `json:"entry_file"`
EntryFiles string `json:"entry_files"`
DesktopShortcutFiles string `json:"desktop_shortcut_files"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
CustomDownloadURL string `json:"custom_download_url"`
Description string `json:"description"`
Changelog string `json:"changelog"`
BaseVersionID *uint `json:"base_version_id"`
Files []VersionFileInput `json:"files"`
}
func handleUpdateVersionGlobal(c *gin.Context) {
@@ -788,6 +825,21 @@ func handleUpdateVersionGlobal(c *gin.Context) {
Details: fmt.Sprintf("更新版本: %s (应用ID: %d)", version.Version, version.ApplicationID),
})
// 只换了包、版本号没动:服务端按「版本记录 ID」判定更新,客户端不会被通知
finalVersion := version.Version
if req.Version != "" {
finalVersion = req.Version
}
if req.FilePath != "" && normalizeVersionStr(finalVersion) == normalizeVersionStr(version.Version) {
log.Printf("[WARN] 版本 %s 替换了文件但版本号未变,客户端不会收到更新通知", finalVersion)
response.Success(c, gin.H{
"warning": "文件已替换,但版本号未变:客户端按版本号判定是否更新,不会收到通知。" +
"请递增版本号,或让客户端在 check-update 时带上 manifest_hash。",
"version": finalVersion,
})
return
}
response.Success(c, nil)
}
@@ -869,10 +921,10 @@ func handleBatchDeleteVersions(c *gin.Context) {
}
type UploadVersionZipResponse struct {
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
Files []VersionFileInfo `json:"files"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
Files []VersionFileInfo `json:"files"`
}
type VersionFileInfo struct {
@@ -1284,3 +1336,11 @@ func handleRollbackVersion(c *gin.Context) {
"publish_status": version.PublishStatus,
})
}
// normalizeVersionStr 版本号归一:去空白、去 v/V 前缀
func normalizeVersionStr(v string) string {
v = strings.TrimSpace(v)
v = strings.TrimPrefix(v, "v")
v = strings.TrimPrefix(v, "V")
return v
}
+27 -12
View File
@@ -248,6 +248,9 @@ func handleAppGetInfo(c *gin.Context) {
func handleAppCheckUpdate(c *gin.Context) {
appKey := c.Param("appKey")
clientVersion := c.Query("version")
// 可选:客户端把自己本地的清单指纹报上来。
// 报了就能发现"版本号没变但文件被重新上传过"的情况;不报则退回按版本记录 ID 判定。
clientManifestHash := strings.TrimSpace(c.Query("manifest_hash"))
var app model.Application
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
@@ -364,18 +367,30 @@ func handleAppCheckUpdate(c *gin.Context) {
if latestVersion.ID > clientVersionRecord.ID {
updateStrategy = latestVersion.UpdateStrategy // optional 或 forced
} else {
// 已经是最新版本
response.Success(c, gin.H{
"has_update": false,
"current_version": clientVersion,
"latest_version": clientVersionRecord.Version,
"download_url": "",
"update_notes": "",
"update_strategy": "",
"update_method": "",
"files": []interface{}{},
})
return
// 版本记录 ID 相同,但客户端报了清单指纹且与服务器不一致
// → 说明该版本号下的文件被重新上传过,仍然下发更新
_, latestManifestHash, _, _ := buildVersionManifest(latestVersion)
contentChanged := clientManifestHash != "" && latestManifestHash != "" &&
clientManifestHash != latestManifestHash
if !contentChanged {
// 已经是最新版本
response.Success(c, gin.H{
"has_update": false,
"current_version": clientVersion,
"latest_version": clientVersionRecord.Version,
"latest_version_id": latestVersion.ID,
"manifest_hash": latestManifestHash,
"reason": "version_record_id_unchanged",
"download_url": "",
"update_notes": "",
"update_strategy": "",
"update_method": "",
"files": []interface{}{},
})
return
}
// 文件内容变了:按最新版本下发
updateStrategy = latestVersion.UpdateStrategy
}
}
+5 -5
View File
@@ -70,7 +70,7 @@ func simulateCheckUpdate(appKey, clientVersion string) (gin.H, error) {
// 安装器模式:客户端没报版本号,直接给最新全量包
if strings.TrimSpace(clientVersion) == "" {
lv := &published[0]
res := packageResult(lv, clientVersion)
res := packageResult(lv, a.AppKey, clientVersion)
res["mode"] = "installer_mode(未上报版本号 → 直接下发最新包)"
res["has_update"] = true
mergeH(base, res)
@@ -95,7 +95,7 @@ func simulateCheckUpdate(appKey, clientVersion string) (gin.H, error) {
// 客户端版本号在服务器里匹配不到 → 整包兜底(新代码行为)
if cur == nil {
lv := &published[0]
res := packageResult(lv, clientVersion)
res := packageResult(lv, a.AppKey, clientVersion)
res["mode"] = "unknown_client_version(客户端版本号在服务器不存在 → 下发最新整包)"
res["has_update"] = true
mergeH(base, res)
@@ -141,7 +141,7 @@ func simulateCheckUpdate(appKey, clientVersion string) (gin.H, error) {
return nil, fmt.Errorf("读取最新版本失败: %w", err)
}
res := packageResult(&lvFull, clientVersion)
res := packageResult(&lvFull, a.AppKey, clientVersion)
res["has_update"] = true
res["update_strategy"] = strategy
res["mode"] = "update"
@@ -154,7 +154,7 @@ func simulateCheckUpdate(appKey, clientVersion string) (gin.H, error) {
}
// packageResult 按 handler 的优先级给出下载地址、hash、清单信息
func packageResult(v *model.Version, clientVersion string) gin.H {
func packageResult(v *model.Version, appKey, clientVersion string) gin.H {
downloadURL := v.FullPackagePath
downloadSize := v.FullPackageSize
downloadHash := v.FullPackageHash
@@ -194,7 +194,7 @@ func packageResult(v *model.Version, clientVersion string) gin.H {
"patch_size": v.FileSize,
"patch_hash": v.FileHash,
"is_patch_delivery": isPatch,
"manifest_url": fmt.Sprintf("/api/v1/app/%s/versions/manifest?version_id=%d", v.Application.AppKey, v.ID),
"manifest_url": fmt.Sprintf("/api/v1/app/%s/versions/manifest?version_id=%d", appKey, v.ID),
"manifest_hash": manifestHash,
"manifest_complete": complete,
"manifest_content_read": stored,
+225 -3
View File
@@ -3,16 +3,21 @@ package mcp
import (
"context"
"crypto/subtle"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"verification-platform-backend/internal/config"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/protect"
"verification-platform-backend/internal/router/app"
"verification-platform-backend/internal/service"
"verification-platform-backend/internal/utils/contentstore"
"github.com/gin-gonic/gin"
sdk "github.com/mark3labs/mcp-go/mcp"
@@ -187,8 +192,8 @@ func registerReadTools(s *mcpserver.MCPServer) {
"desktop_shortcut_files": v.DesktopShortcutFiles,
"description": v.Description, "changelog": v.Changelog,
"manifest_hash": manifestHash, "manifest_complete": complete, "content_stored": stored,
"files": files,
"created_at": v.CreatedAt, "updated_at": v.UpdatedAt,
"files": files,
"created_at": v.CreatedAt, "updated_at": v.UpdatedAt,
})
})
@@ -374,10 +379,65 @@ func registerReadTools(s *mcpserver.MCPServer) {
}
return sdk.NewToolResultJSON(gin.H{"total": len(items), "logs": items})
})
// ---------- 加壳任务(只读) ----------
s.AddTool(sdk.NewTool("verify_list_protect_tasks",
sdk.WithDescription("列出加壳任务(给程序注入验证壳的任务)。可按应用与状态过滤,按 id 倒序。"),
sdk.WithNumber("app_id", sdk.Description("应用 ID,省略则全部")),
sdk.WithString("status", sdk.Description("pending/running/done/failed")),
sdk.WithNumber("limit", sdk.Description("返回条数,默认 20,最大 100")),
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
limit := int(req.GetFloat("limit", 20))
if limit < 1 || limit > 100 {
limit = 20
}
q := database.DB.Model(&model.ProtectTask{})
if appID := req.GetInt("app_id", 0); appID > 0 {
q = q.Where("application_id = ?", appID)
}
if st := req.GetString("status", ""); st != "" {
q = q.Where("status = ?", st)
}
var tasks []model.ProtectTask
if err := q.Order("id DESC").Limit(limit).Find(&tasks).Error; err != nil {
return sdk.NewToolResultErrorFromErr("查询加壳任务失败", err), nil
}
items := make([]gin.H, 0, len(tasks))
for _, t := range tasks {
items = append(items, gin.H{
"id": t.ID, "application_id": t.ApplicationID, "source_name": t.SourceName,
"source_size": t.SourceSize, "arch": t.Arch, "status": t.Status,
"message": t.Message, "output_name": t.OutputName, "output_size": t.OutputSize,
"crc_vfy": t.CrcVfy, "crc_file": t.CrcFile,
"created_at": t.CreatedAt, "finished_at": t.FinishedAt,
})
}
return sdk.NewToolResultJSON(gin.H{"total": len(items), "tasks": items})
})
s.AddTool(sdk.NewTool("verify_get_protect_task",
sdk.WithDescription("查看单个加壳任务详情:状态、错误信息、产物文件名/大小、双层 CRC。"),
sdk.WithNumber("task_id", sdk.Required(), sdk.Description("任务 ID")),
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
id := req.GetInt("task_id", 0)
if id <= 0 {
return sdk.NewToolResultError("task_id 必须为正整数"), nil
}
var t model.ProtectTask
if err := database.DB.First(&t, id).Error; err != nil {
return sdk.NewToolResultError("任务不存在"), nil
}
return sdk.NewToolResultJSON(gin.H{
"id": t.ID, "application_id": t.ApplicationID, "source_name": t.SourceName,
"source_size": t.SourceSize, "arch": t.Arch, "status": t.Status,
"message": t.Message, "output_name": t.OutputName, "output_size": t.OutputSize,
"output_path": t.OutputPath, "crc_vfy": t.CrcVfy, "crc_file": t.CrcFile,
"created_at": t.CreatedAt, "started_at": t.StartedAt, "finished_at": t.FinishedAt,
})
})
}
func registerWriteTools(s *mcpserver.MCPServer) {
// ---------- 发布版本 ----------
s.AddTool(sdk.NewTool("verify_publish_version",
sdk.WithDescription("发布版本。规则与面板一致:仅 draft/deprecated 可发布;forced 策略会把更早的 published 版本置为 superseded。dry_run=true 只返回将要发生的变化。"),
sdk.WithDestructiveHintAnnotation(true),
@@ -486,6 +546,168 @@ func registerWriteTools(s *mcpserver.MCPServer) {
"publish_status": v.PublishStatus, "restored_version_ids": restored,
})
})
// ---------- 给版本加壳 ----------
s.AddTool(sdk.NewTool("verify_protect_version",
sdk.WithDescription("给某个版本的入口 exe 注入验证壳(改入口 + 内存加载壳 DLL + 双层 CRC32),产出单文件、可直接分发的 exe。同步执行,返回产物路径/大小/CRC。dry_run=true 只报告将用哪个文件加壳。"),
sdk.WithDestructiveHintAnnotation(true),
sdk.WithNumber("version_id", sdk.Required(), sdk.Description("版本记录 ID")),
sdk.WithBoolean("dry_run", sdk.Description("只报告不改动,默认 true")),
sdk.WithString("base_url", sdk.Description("产物验证接口的站点根地址,如 https://v.viaeon.com;省略则读配置 protect.base_url")),
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
vid := req.GetInt("version_id", 0)
if vid <= 0 {
return sdk.NewToolResultError("version_id 必须为正整数"), nil
}
var v model.Version
if err := database.DB.First(&v, vid).Error; err != nil {
return sdk.NewToolResultError("版本不存在"), nil
}
var app model.Application
if err := database.DB.First(&app, v.ApplicationID).Error; err != nil {
return sdk.NewToolResultError("应用不存在"), nil
}
var files []model.VersionFile
database.DB.Where("version_id = ?", v.ID).Find(&files)
chosen, err := pickEntryExe(&v, files)
if err != nil {
return sdk.NewToolResultErrorFromErr("找不到可加壳的入口 exe", err), nil
}
srcPath := contentstore.ContentFilePath(chosen.FileHash)
if err := protect.WaitSource(srcPath); err != nil {
contentstore.ExtractOnDemand(v.FilePath)
if err := protect.WaitSource(srcPath); err != nil {
return sdk.NewToolResultError("入口文件还没解包到服务器本地,请稍后重试: " + err.Error()), nil
}
}
data, err := os.ReadFile(srcPath)
if err != nil {
return sdk.NewToolResultErrorFromErr("读取入口文件失败", err), nil
}
arch, err := protect.DetectArch(data)
if err != nil {
return sdk.NewToolResultError("入口文件不是有效 PE: " + err.Error()), nil
}
if req.GetBool("dry_run", true) {
return sdk.NewToolResultJSON(gin.H{
"dry_run": true, "version_id": v.ID, "version": v.Version,
"app_key": app.AppKey, "app_name": app.Name,
"entry_file": chosen.FileName, "source_size": len(data), "arch": arch,
})
}
base := req.GetString("base_url", "")
if base == "" {
base = config.GetString("protect.base_url")
}
if base == "" {
return sdk.NewToolResultError("缺少 base_url:请传参或配置 protect.base_url(产物靠它找到验证接口)"), nil
}
task, info, err := protect.CreateAndRunSyncWithVersion(&app, app.UserID, chosen.FileName, data, base, v.ID)
if err != nil {
return sdk.NewToolResultErrorFromErr("加壳失败", err), nil
}
return sdk.NewToolResultJSON(gin.H{
"dry_run": false, "task_id": task.ID, "version_id": v.ID, "version": v.Version,
"entry_file": chosen.FileName, "arch": info.Arch,
"source_size": info.OriginalSource, "output_size": info.OutSize,
"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 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}
}
}
planned := opts.Version
if planned == "" && task.VersionID > 0 {
var src model.Version
if database.DB.First(&src, task.VersionID).Error == nil {
planned = protect.BumpVersion(src.Version) + "(自动进位,若已占用会继续往上找)"
}
}
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": planned, "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,
})
})
}
// pickEntryExe 从版本文件里挑出入口 exe:优先 version.entry_file 同名项,退化到第一个 .exe
func pickEntryExe(v *model.Version, files []model.VersionFile) (*model.VersionFile, error) {
want := strings.ToLower(filepath.Base(v.EntryFile))
if want != "" && want != "." {
for i := range files {
if strings.ToLower(filepath.Base(files[i].FileName)) == want {
return &files[i], nil
}
}
}
for i := range files {
if strings.HasSuffix(strings.ToLower(files[i].FileName), ".exe") {
return &files[i], nil
}
}
return nil, fmt.Errorf("版本 %s 里没有 .exe(共 %d 个文件)", v.Version, len(files))
}
// auditLog 把 MCP 写操作记进 verify 自己的 logs 表(user_id 留空表示系统/MCP 操作)
@@ -1,5 +1,5 @@
<script lang="ts" setup>
import { Boxes, Code, CreditCard, DollarSign, FileLock, Gauge, GitBranch, HardDrive, Hash, Key, KeyRound, Mail, Megaphone, MessageSquare, Monitor, Network, Plug, ScrollText, Settings, Shield, Smartphone, Users, Variable } from 'lucide-vue-next'
import { Boxes, Code, CreditCard, DollarSign, FileLock, Gauge, GitBranch, HardDrive, Hash, Key, KeyRound, Mail, Megaphone, MessageSquare, Monitor, Network, PackageCheck, Plug, ScrollText, Settings, Shield, Smartphone, Users, Variable } from 'lucide-vue-next'
import { computed, onMounted, reactive, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { usePreferredDark } from '@vueuse/core'
@@ -99,6 +99,11 @@ const navMain = computed(() => [
url: '/admin/versions',
icon: GitBranch,
},
{
title: t('nav.protect'),
url: '/admin/protect',
icon: PackageCheck,
},
{
title: t('nav.users'),
url: '/admin/users',
+1
View File
@@ -23,6 +23,7 @@ const breadcrumbs = computed(() => {
sessions: t('nav.sessions'),
announcements: t('nav.announcements'),
versions: t('nav.versions'),
protect: t('nav.protect'),
'card-types': t('nav.cardTypes'),
'agent-apps': t('nav.agentApps'),
agents: t('nav.agents'),
+594
View File
@@ -0,0 +1,594 @@
<script setup lang="ts">
import type { Component } from 'vue'
import { CheckCircle2, FileUp, Loader2, PackageCheck, RefreshCw, ShieldCheck, Trash2, XCircle } from 'lucide-vue-next'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { toast } from 'vue-sonner'
import { BasicPage } from '@/components/global-layout'
import api, { BASE_URL } from '@/services/api'
const { t } = useI18n()
interface AppItem {
id: number
name: string
app_key: string
}
interface Task {
id: number
application_id: number
source_name: string
source_size: number
arch: string
status: 'pending' | 'running' | 'done' | 'failed'
message: string
output_name: string
output_size: number
crc_vfy: string
crc_file: string
created_at: string
finished_at: string | null
}
const apps = ref<AppItem[]>([])
const tasks = ref<Task[]>([])
const total = ref(0)
const loading = ref(true)
const selectedApp = ref<string>('')
const fileInput = ref<HTMLInputElement | null>(null)
const chosenFile = ref<File | null>(null)
const uploading = ref(false)
const uploadProgress = ref(0)
const dragging = ref(false)
const statusFilter = ref<string>('')
let timer: number | undefined
const pendingCount = computed(() => tasks.value.filter(t => t.status === 'pending' || t.status === 'running').length)
const doneCount = computed(() => tasks.value.filter(t => t.status === 'done').length)
const failedCount = computed(() => tasks.value.filter(t => t.status === 'failed').length)
function authHeaders(): Record<string, string> {
const token = localStorage.getItem('token')
const headers: Record<string, string> = {}
if (token)
headers.Authorization = `Bearer ${token}`
return headers
}
async function loadApps() {
try {
const data = await api.get<{ applications: AppItem[] }>('/dev/applications')
apps.value = data?.applications || []
if (!selectedApp.value && apps.value.length)
selectedApp.value = String(apps.value[0].id)
}
catch (e: any) {
toast.error(e.message || t('admin.protect.loadAppsFailed'))
}
}
async function loadTasks() {
const q = new URLSearchParams({ per_page: '50', page: '1' })
if (statusFilter.value)
q.set('status', statusFilter.value)
try {
const res = await fetch(`${BASE_URL}/dev/protect/tasks?${q}`, { headers: authHeaders() })
const body = await res.json()
if (body?.code !== 0 && body?.code !== 200)
throw new Error(body?.message || t('admin.protect.loadFailed'))
tasks.value = Array.isArray(body.data) ? body.data : (body.data?.list || [])
total.value = body.total ?? tasks.value.length
}
catch (e: any) {
toast.error(e.message || t('admin.protect.loadFailed'))
}
finally {
loading.value = false
}
schedulePoll()
}
// 有任务在跑时每 2 秒刷新一次
function schedulePoll() {
if (timer)
window.clearTimeout(timer)
if (pendingCount.value > 0)
timer = window.setTimeout(loadTasks, 2000)
}
function pickFile(file: File | null | undefined) {
if (!file)
return
if (!file.name.toLowerCase().endsWith('.exe')) {
toast.error(t('admin.protect.onlyExe'))
return
}
if (file.size > 200 * 1024 * 1024) {
toast.error(t('admin.protect.tooLarge'))
return
}
chosenFile.value = file
}
function onFileChange(e: Event) {
const input = e.target as HTMLInputElement
pickFile(input.files?.[0])
input.value = ''
}
function onDrop(e: DragEvent) {
dragging.value = false
pickFile(e.dataTransfer?.files?.[0])
}
async function startProtect() {
if (!selectedApp.value) {
toast.error(t('admin.protect.pickApp'))
return
}
if (!chosenFile.value) {
toast.error(t('admin.protect.pickFile'))
return
}
uploading.value = true
uploadProgress.value = 0
try {
const fd = new FormData()
fd.append('application_id', selectedApp.value)
fd.append('file', chosenFile.value)
await api.postFormDataWithProgress(
'/dev/protect/tasks',
fd,
(p) => { uploadProgress.value = p },
)
toast.success(t('admin.protect.queued'))
chosenFile.value = null
await loadTasks()
}
catch (e: any) {
toast.error(e.message || t('admin.protect.failed'))
}
finally {
uploading.value = false
uploadProgress.value = 0
}
}
function downloadTask(task: Task) {
const token = localStorage.getItem('token') || ''
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'))
return
}
try {
await api.delete(`/dev/protect/tasks/${task.id}`)
toast.success(t('admin.protect.deleted'))
await loadTasks()
}
catch (e: any) {
toast.error(e.message || t('admin.protect.failed'))
}
}
function formatSize(bytes: number) {
if (!bytes)
return '-'
if (bytes < 1024)
return `${bytes} B`
if (bytes < 1024 * 1024)
return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / 1024 / 1024).toFixed(2)} MB`
}
function formatTime(v: string | null) {
if (!v)
return '-'
return new Date(v).toLocaleString()
}
function appName(id: number) {
return apps.value.find(a => a.id === id)?.name || `#${id}`
}
const statusStyle: Record<string, string> = {
pending: 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30',
running: 'bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/30',
done: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30',
failed: 'bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/30',
}
const statusIcon: Record<string, Component> = {
pending: Loader2,
running: Loader2,
done: CheckCircle2,
failed: XCircle,
}
onMounted(async () => {
await loadApps()
await loadTasks()
})
onBeforeUnmount(() => {
if (timer)
window.clearTimeout(timer)
})
</script>
<template>
<BasicPage :title="t('admin.protect.title')" :description="t('admin.protect.description')" sticky>
<template #actions>
<div class="flex items-center gap-2">
<select
v-model="statusFilter"
class="h-9 rounded-md border border-input bg-background px-3 text-sm"
@change="loadTasks"
>
<option value="">
{{ t('admin.protect.allStatus') }}
</option>
<option value="pending">
{{ t('admin.protect.statusPending') }}
</option>
<option value="running">
{{ t('admin.protect.statusRunning') }}
</option>
<option value="done">
{{ t('admin.protect.statusDone') }}
</option>
<option value="failed">
{{ t('admin.protect.statusFailed') }}
</option>
</select>
<UiButton variant="outline" :disabled="loading" @click="loadTasks">
<RefreshCw class="mr-2 h-4 w-4" :class="{ 'animate-spin': loading }" />
{{ t('admin.protect.refresh') }}
</UiButton>
</div>
</template>
<div class="space-y-6">
<!-- 概览 -->
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('admin.protect.totalTasks') }}
</UiCardTitle>
<PackageCheck class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold">
{{ total }}
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('admin.protect.inProgress') }}
</UiCardTitle>
<Loader2 class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold text-blue-600 dark:text-blue-400">
{{ pendingCount }}
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('admin.protect.doneCount') }}
</UiCardTitle>
<ShieldCheck class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
{{ doneCount }}
</div>
</UiCardContent>
</UiCard>
<UiCard>
<UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
<UiCardTitle class="text-sm font-medium">
{{ t('admin.protect.failedCount') }}
</UiCardTitle>
<XCircle class="size-4 text-muted-foreground" />
</UiCardHeader>
<UiCardContent>
<div class="text-2xl font-bold text-red-600 dark:text-red-400">
{{ failedCount }}
</div>
</UiCardContent>
</UiCard>
</div>
<!-- 上传 -->
<UiCard>
<UiCardHeader>
<UiCardTitle class="text-base">
{{ t('admin.protect.uploadTitle') }}
</UiCardTitle>
<p class="text-sm text-muted-foreground">
{{ t('admin.protect.uploadHint') }}
</p>
</UiCardHeader>
<UiCardContent class="space-y-4">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
<label class="text-sm font-medium shrink-0">{{ t('admin.protect.app') }}</label>
<select
v-model="selectedApp"
class="h-9 w-full rounded-md border border-input bg-background px-3 text-sm sm:max-w-xs"
>
<option v-for="a in apps" :key="a.id" :value="String(a.id)">
{{ a.name }} ({{ a.app_key }})
</option>
</select>
</div>
<div
class="rounded-lg border-2 border-dashed p-6 text-center transition-colors"
:class="dragging ? 'border-primary bg-primary/5' : 'border-input'"
@dragover.prevent="dragging = true"
@dragleave.prevent="dragging = false"
@drop.prevent="onDrop"
@click="fileInput?.click()"
>
<input ref="fileInput" type="file" accept=".exe" class="hidden" @change="onFileChange">
<FileUp class="mx-auto mb-2 h-8 w-8 text-muted-foreground" />
<template v-if="chosenFile">
<p class="text-sm font-medium">
{{ chosenFile.name }}
</p>
<p class="text-xs text-muted-foreground">
{{ formatSize(chosenFile.size) }}
</p>
</template>
<template v-else>
<p class="text-sm text-muted-foreground">
{{ t('admin.protect.dropHint') }}
</p>
</template>
</div>
<div v-if="uploading" class="space-y-1">
<div class="h-2 w-full overflow-hidden rounded-full bg-muted">
<div class="h-full bg-primary transition-all" :style="{ width: `${uploadProgress}%` }" />
</div>
<p class="text-xs text-muted-foreground">
{{ t('admin.protect.uploading') }} {{ uploadProgress }}%
</p>
</div>
<div class="flex items-center gap-2">
<UiButton :disabled="uploading || !chosenFile" @click="startProtect">
<ShieldCheck class="mr-2 h-4 w-4" />
{{ t('admin.protect.start') }}
</UiButton>
<UiButton v-if="chosenFile" variant="ghost" @click="chosenFile = null">
{{ t('admin.protect.clear') }}
</UiButton>
</div>
</UiCardContent>
</UiCard>
<!-- 任务列表 -->
<UiCard>
<UiCardHeader>
<UiCardTitle class="text-base">
{{ t('admin.protect.tasks') }}
</UiCardTitle>
</UiCardHeader>
<UiCardContent>
<div v-if="loading" class="flex items-center gap-2 py-8 text-sm text-muted-foreground">
<Loader2 class="h-4 w-4 animate-spin" />
{{ t('admin.protect.loading') }}
</div>
<div v-else-if="!tasks.length" class="py-10 text-center text-sm text-muted-foreground">
{{ t('admin.protect.empty') }}
</div>
<div v-else class="overflow-x-auto">
<table class="w-full text-sm">
<thead class="border-b text-left text-muted-foreground">
<tr>
<th class="px-2 py-2 font-medium">
#
</th>
<th class="px-2 py-2 font-medium">
{{ t('admin.protect.app') }}
</th>
<th class="px-2 py-2 font-medium">
{{ t('admin.protect.source') }}
</th>
<th class="px-2 py-2 font-medium">
{{ t('admin.protect.arch') }}
</th>
<th class="px-2 py-2 font-medium">
{{ t('admin.protect.status') }}
</th>
<th class="px-2 py-2 font-medium">
CRC
</th>
<th class="px-2 py-2 font-medium">
{{ t('admin.protect.createdAt') }}
</th>
<th class="px-2 py-2 text-right font-medium">
{{ t('admin.protect.actions') }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="task in tasks" :key="task.id" class="border-b last:border-0 align-top">
<td class="px-2 py-3 text-muted-foreground">
{{ task.id }}
</td>
<td class="px-2 py-3">
{{ appName(task.application_id) }}
</td>
<td class="px-2 py-3">
<div class="font-medium break-all">
{{ task.source_name }}
</div>
<div class="text-xs text-muted-foreground">
{{ formatSize(task.source_size) }} → {{ formatSize(task.output_size) }}
</div>
<div v-if="task.status === 'failed' && task.message" class="mt-1 text-xs text-red-600 dark:text-red-400 break-all">
{{ task.message }}
</div>
</td>
<td class="px-2 py-3">
<span class="rounded border px-1.5 py-0.5 text-xs">{{ task.arch || '-' }}</span>
</td>
<td class="px-2 py-3">
<span
class="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs"
:class="statusStyle[task.status] || 'border-input'"
>
<component
:is="statusIcon[task.status]" class="h-3 w-3"
:class="{ 'animate-spin': task.status === 'running' }"
/>
{{ t(`admin.protect.status${task.status.charAt(0).toUpperCase()}${task.status.slice(1)}`) }}
</span>
</td>
<td class="px-2 py-3 font-mono text-xs text-muted-foreground">
<div v-if="task.crc_vfy">
vfy {{ task.crc_vfy }}
</div>
<div v-if="task.crc_file">
file {{ task.crc_file }}
</div>
</td>
<td class="px-2 py-3 text-xs text-muted-foreground">
{{ formatTime(task.created_at) }}
</td>
<td class="px-2 py-3">
<div class="flex justify-end gap-1">
<UiButton
size="sm"
variant="outline"
:disabled="task.status !== 'done'"
@click="downloadTask(task)"
>
{{ 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>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</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>
+35 -1
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { Check, CheckCircle, Eye, FileArchive, FilePlus, GitBranch, Loader2, Upload, UploadCloud, X } from 'lucide-vue-next'
import { Check, CheckCircle, Eye, FileArchive, FilePlus, GitBranch, Loader2, Upload, UploadCloud, X, ShieldCheck } from 'lucide-vue-next'
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
@@ -129,11 +129,24 @@ function toggleDesktopShortcut(filePath: string) {
}
}
const protectInfo = ref<{ protected: boolean, sourceVersion: string, sourceVersionId: number | null, taskId: number | null }>({
protected: false,
sourceVersion: '',
sourceVersionId: null,
taskId: null,
})
async function fetchVersion() {
loading.value = true
try {
const ver = await api.get<any>(`/dev/versions/${versionId.value}`)
if (ver) {
protectInfo.value = {
protected: !!ver.protected,
sourceVersion: ver.source_version || '',
sourceVersionId: ver.source_version_id ?? null,
taskId: ver.protect_task_id ?? null,
}
formData.value.application_id = String(ver.application_id || '')
formData.value.version = ver.version || ''
formData.value.description = ver.description || ''
@@ -424,6 +437,27 @@ onMounted(() => {
</div>
<div v-else class="space-y-6">
<!-- 加壳来源提示 -->
<div
v-if="protectInfo.protected"
class="flex flex-wrap items-center gap-3 rounded-lg border border-emerald-500/30 bg-emerald-500/5 px-4 py-3 text-sm"
>
<ShieldCheck class="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
<span class="font-medium text-emerald-700 dark:text-emerald-300">{{ t('admin.versions.protectedBanner') }}</span>
<span v-if="protectInfo.sourceVersion" class="text-muted-foreground">
{{ t('admin.versions.derivedFrom') }}
<code class="ml-1 rounded bg-muted px-1.5 py-0.5">{{ protectInfo.sourceVersion }}</code>
</span>
<span v-else class="text-muted-foreground">{{ t('admin.versions.sourceUnknown') }}</span>
<RouterLink
v-if="protectInfo.taskId"
:to="`/admin/protect`"
class="ml-auto text-xs text-primary underline-offset-4 hover:underline"
>
{{ t('admin.versions.viewProtectTask', { id: protectInfo.taskId }) }}
</RouterLink>
</div>
<div class="grid gap-6 lg:grid-cols-3">
<div class="lg:col-span-2 space-y-6">
<UiCard>
@@ -1,4 +1,4 @@
import { Download, Edit, Trash2, Upload, Archive, ArrowDownToLine, Package } from 'lucide-vue-next'
import { Download, Edit, Trash2, Upload, Archive, ArrowDownToLine, Package, ShieldCheck, UploadCloud } from 'lucide-vue-next'
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
@@ -34,7 +34,39 @@ export function getColumns(options: ColumnOptions, t: (key: string) => string):
accessorKey: 'version',
header: () => t('admin.versions.columns.version'),
cell: ({ row }) => {
return h('code', { class: 'text-sm bg-muted px-2 py-1 rounded' }, row.original.version)
const code = h('code', { class: 'text-sm bg-muted px-2 py-1 rounded' }, row.original.version)
if (!row.original.protected)
return code
const tag = h(Badge, {
variant: 'outline',
class: 'ml-1.5 gap-1 border-emerald-500/40 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
title: t('admin.versions.protectedHint'),
}, () => [h(ShieldCheck, { class: 'h-3 w-3' }), h('span', {}, t('admin.versions.protectedBadge'))])
return h('div', { class: 'flex items-center' }, [code, tag])
},
},
{
id: 'source_version',
header: () => t('admin.versions.columns.sourceVersion'),
cell: ({ row }) => {
const src = row.original.source_version
const muted = 'flex items-center gap-1 text-xs text-muted-foreground'
if (!row.original.protected)
return h('span', { class: muted }, [h('span', { class: 'inline-block h-3 w-3 shrink-0' }), h('span', {}, '-')])
if (!row.original.source_version_id)
return h('span', { class: muted }, [
h(UploadCloud, { class: 'h-3 w-3 shrink-0' }),
h('span', {}, t('admin.versions.sourceDirect')),
])
if (!src)
return h('span', { class: muted }, [
h(UploadCloud, { class: 'h-3 w-3 shrink-0' }),
h('span', {}, t('admin.versions.sourceUnknown')),
])
return h('div', { class: 'flex items-center gap-1' }, [
h(ArrowDownToLine, { class: 'h-3 w-3 text-muted-foreground' }),
h('code', { class: 'text-xs bg-muted px-1.5 py-0.5 rounded' }, src),
])
},
},
{
@@ -20,6 +20,10 @@ export const versionSchema = z.object({
status: z.string(), // 兼容旧字段
publish_status: publishStatusSchema,
superseded_by: z.number().nullable().optional(),
protected: z.boolean().optional(),
source_version_id: z.number().nullable().optional(),
protect_task_id: z.number().nullable().optional(),
source_version: z.string().optional(),
published_at: z.string().nullable().optional(),
deprecated_at: z.string().nullable().optional(),
changelog: z.string(),
+80 -28
View File
@@ -275,15 +275,10 @@
"applicationRequired": "Please select application",
"deviceId": "Device ID",
"deviceIdPlaceholder": "Device ID (optional)",
"preview": "Preview",
"app": "Application",
"usernameLabel": "Username",
"emailLabel": "Email",
"deviceIdLabel": "Device ID",
"status": "Account Status",
"onlineStatus": "Online Status",
"submit": "Save",
"cancel": "Cancel",
"fetchFailed": "Failed to fetch user information",
"success": "User updated successfully",
"failed": "Failed to update user",
@@ -1156,14 +1151,13 @@
"editSuccess": "Card type updated successfully",
"create": {
"title": "Create Card Type",
"description": "Create a new card type with basic information and recharge configuration",
"description": "Batch generate cards",
"basicInfo": "Basic Information",
"basicInfoDesc": "Fill in the basic information of the card type",
"billingConfig": "Billing Configuration",
"billingConfigDesc": "Select the billing method and value settings",
"name": "Type Name",
"namePlaceholder": "Enter type name",
"description": "Batch generate cards",
"descriptionPlaceholder": "Enter description",
"application": "Application",
"selectApplication": "Select application",
@@ -1437,7 +1431,8 @@
"status": "Status",
"deltaPackage": "Delta",
"createdAt": "Created At",
"actions": "Actions"
"actions": "Actions",
"sourceVersion": "Derived from"
},
"actions": {
"download": "Download",
@@ -1549,7 +1544,14 @@
"updateFailed": "Failed to update version",
"fetchFailed": "Failed to fetch version information",
"fetchAppsFailed": "Failed to fetch application list"
}
},
"protectedBadge": "Protected",
"protectedHint": "This version is a protected artifact with the verification shell",
"protectedBanner": "This version was generated by the protect tool",
"derivedFrom": "derived from",
"sourceUnknown": "source version removed",
"viewProtectTask": "View protect task #{id}",
"sourceDirect": "uploaded & protected"
},
"cardTypes": {
"title": "Card Type Management",
@@ -2195,7 +2197,14 @@
"batchUpdateSuccess": "Batch update successful",
"batchUpdateFailed": "Batch update failed",
"select": "Select",
"edit": "Edit",
"edit": {
"title": "Edit Cloud Function",
"titleDescription": "Edit cloud function configuration",
"config": "Configuration",
"configDesc": "Edit cloud function basic information and code",
"submitBtn": "Save",
"cancelBtn": "Cancel"
},
"editSuccess": "Updated successfully",
"editFailed": "Failed to fetch cloud function",
"columns": {
@@ -2233,14 +2242,6 @@
"submitSuccess": "Created successfully",
"submitFailed": "Failed to create"
},
"edit": {
"title": "Edit Cloud Function",
"titleDescription": "Edit cloud function configuration",
"config": "Configuration",
"configDesc": "Edit cloud function basic information and code",
"submitBtn": "Save",
"cancelBtn": "Cancel"
},
"updateSuccess": "Updated successfully",
"updateFailed": "Failed to update",
"fetchFailed": "Failed to fetch cloud function"
@@ -2569,6 +2570,60 @@
"faviconSuccess": "Favicon uploaded successfully",
"uploadFailed": "Upload failed"
}
},
"protect": {
"title": "Protection",
"description": "Inject a verification shell into your program: entry rewrite + in-memory DLL + dual CRC32, single-file output",
"totalTasks": "Total tasks",
"inProgress": "In progress",
"doneCount": "Completed",
"failedCount": "Failed",
"uploadTitle": "Upload program",
"uploadHint": "32/64-bit Windows PE, up to 200MB. Output is unsigned — Windows will warn about unknown publisher",
"app": "Application",
"dropHint": "Click to choose or drop an .exe file",
"onlyExe": "Only .exe files are supported",
"tooLarge": "File too large (max 200MB)",
"pickApp": "Choose an application first",
"pickFile": "Choose a program first",
"queued": "Submitted, protecting…",
"uploading": "Uploading",
"start": "Start",
"clear": "Clear",
"tasks": "Protection tasks",
"source": "Source / output",
"arch": "Arch",
"status": "Status",
"createdAt": "Created",
"actions": "Actions",
"download": "Download",
"refresh": "Refresh",
"loading": "Loading…",
"empty": "No protection tasks yet",
"allStatus": "All status",
"statusPending": "Queued",
"statusRunning": "Protecting",
"statusDone": "Completed",
"statusFailed": "Failed",
"busy": "Task is running, try later",
"deleted": "Deleted",
"failed": "Operation failed",
"loadFailed": "Failed to load tasks",
"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": {
@@ -2809,7 +2864,11 @@
"noUsers": "No user records yet",
"username": "Username",
"email": "Email",
"status": "Status",
"status": {
"active": "Active",
"disabled": "Disabled",
"banned": "Banned"
},
"registerTime": "Register Time",
"lastLogin": "Last Login",
"active": "Active",
@@ -2845,11 +2904,6 @@
"expired": "Expired",
"daysLeft": "days left"
},
"status": {
"active": "Active",
"disabled": "Disabled",
"banned": "Banned"
},
"create": {
"title": "Create User",
"description": "Create a new user under your application",
@@ -2950,7 +3004,6 @@
"exportBtn": "Export",
"batchExportBtn": "Batch Export",
"application": "Application",
"cardType": "Card Type",
"reset": "Reset",
"select": "Select",
"columns": {
@@ -2998,7 +3051,6 @@
"application": "Select Application",
"selectApplication": "Please select an application",
"cardType": "Select Card Type",
"selectCardType": "Please select a card type",
"noCardType": "No available card types for this application",
"count": "Quantity",
"maxCount": "Maximum 100 cards per generation",
@@ -3006,7 +3058,6 @@
"app": "Application",
"type": "Card Type",
"unitPrice": "Unit Price",
"quantity": "Quantity",
"units": "cards",
"totalAmount": "Estimated Cost",
"generateNow": "Generate Now"
@@ -3222,7 +3273,8 @@
"normal": "Normal",
"storage": "Storage",
"admin": "Admin",
"agent": "Agent"
"agent": "Agent",
"protect": "Protection"
},
"footer": {
"brand": "Weishouquan",
+83 -43
View File
@@ -275,15 +275,10 @@
"applicationRequired": "请选择应用",
"deviceId": "设备指纹",
"deviceIdPlaceholder": "设备指纹(可选)",
"preview": "预览",
"app": "应用",
"usernameLabel": "用户名",
"emailLabel": "邮箱",
"deviceIdLabel": "设备指纹",
"status": "账户状态",
"onlineStatus": "在线状态",
"submit": "保存",
"cancel": "取消",
"fetchFailed": "获取用户信息失败",
"success": "保存成功",
"failed": "保存失败",
@@ -1311,8 +1306,7 @@
"save": "保存",
"usernameHint": "用户名不可修改",
"passwordPlaceholder": "留空则不修改密码",
"passwordHint": "输入新密码以修改,留空保持原密码",
"saveBtn": "保存修改"
"passwordHint": "如需修改密码请输入新密码,留空则保持原密码"
},
"editSuccess": "更新代理成功",
"editFailed": "更新代理失败",
@@ -1332,18 +1326,7 @@
"batchDeleteSuccess": "批量删除成功",
"batchDeleteFailed": "批量删除失败",
"batchUpdateSuccess": "批量更新成功",
"batchUpdateFailed": "批量更新失败",
"edit": {
"title": "编辑代理",
"description": "修改代理信息",
"fetchFailed": "获取代理信息失败",
"saveSuccess": "保存成功",
"saveFailed": "保存失败",
"save": "保存",
"usernameHint": "用户名不可修改",
"passwordPlaceholder": "留空则不修改密码",
"passwordHint": "如需修改密码请输入新密码,留空则保持原密码"
}
"batchUpdateFailed": "批量更新失败"
},
"announcements": {
"title": "公告管理",
@@ -1433,7 +1416,8 @@
"status": "状态",
"deltaPackage": "增量包",
"createdAt": "创建时间",
"actions": "操作"
"actions": "操作",
"sourceVersion": "派生自"
},
"actions": {
"download": "下载",
@@ -1556,7 +1540,14 @@
"updateFailed": "更新失败",
"fetchFailed": "获取版本信息失败",
"fetchAppsFailed": "获取应用列表失败"
}
},
"protectedBadge": "已加固",
"protectedHint": "此版本是加壳产物,入口文件带验证壳",
"protectedBanner": "此版本由加壳工具生成",
"derivedFrom": "派生自",
"sourceUnknown": "来源版本已删除",
"viewProtectTask": "查看加壳任务 #{id}",
"sourceDirect": "直接上传加壳"
},
"cardTypes": {
"title": "卡类管理",
@@ -1592,14 +1583,13 @@
"editSuccess": "更新卡类成功",
"create": {
"title": "创建卡类",
"description": "创建新的卡密类型,设置基本信息和充值配置",
"description": "描述",
"basicInfo": "基本信息",
"basicInfoDesc": "填写卡类的基本信息",
"billingConfig": "充值配置",
"billingConfigDesc": "设置卡密充值金额",
"name": "类型名称",
"namePlaceholder": "请输入类型名称",
"description": "描述",
"descriptionPlaceholder": "请输入描述",
"application": "所属应用",
"selectApplication": "请选择应用",
@@ -2226,7 +2216,14 @@
"batchUpdateSuccess": "批量更新成功",
"batchUpdateFailed": "批量更新失败",
"select": "选择",
"edit": "编辑",
"edit": {
"title": "编辑云端函数",
"titleDescription": "编辑云端函数配置",
"config": "配置",
"configDesc": "编辑云端函数的基本信息和代码",
"submitBtn": "保存",
"cancelBtn": "取消"
},
"editSuccess": "更新成功",
"editFailed": "获取云端函数失败",
"columns": {
@@ -2264,14 +2261,6 @@
"submitSuccess": "创建成功",
"submitFailed": "创建失败"
},
"edit": {
"title": "编辑云端函数",
"titleDescription": "编辑云端函数配置",
"config": "配置",
"configDesc": "编辑云端函数的基本信息和代码",
"submitBtn": "保存",
"cancelBtn": "取消"
},
"updateSuccess": "更新成功",
"updateFailed": "更新失败",
"fetchFailed": "获取云端函数失败"
@@ -2600,6 +2589,60 @@
"faviconSuccess": "图标上传成功",
"uploadFailed": "上传失败"
}
},
"protect": {
"title": "加壳加固",
"description": "给程序注入验证壳:改入口 + 内存加载壳 DLL + 双层 CRC32,产物单文件、免安装依赖",
"totalTasks": "任务总数",
"inProgress": "进行中",
"doneCount": "已完成",
"failedCount": "失败",
"uploadTitle": "上传程序",
"uploadHint": "支持 32 / 64 位 Windows PE,最大 200MB;产物未签名,Windows 会提示未知发布者",
"app": "应用",
"dropHint": "点击选择或拖入 .exe 文件",
"onlyExe": "只支持 .exe 文件",
"tooLarge": "文件过大(上限 200MB)",
"pickApp": "请先选择应用",
"pickFile": "请先选择要加壳的程序",
"queued": "已提交,正在加壳",
"uploading": "上传中",
"start": "开始加壳",
"clear": "清除",
"tasks": "加壳任务",
"source": "源文件 / 产物",
"arch": "架构",
"status": "状态",
"createdAt": "创建时间",
"actions": "操作",
"download": "下载",
"refresh": "刷新",
"loading": "加载中…",
"empty": "还没有加壳任务",
"allStatus": "全部状态",
"statusPending": "排队中",
"statusRunning": "加壳中",
"statusDone": "已完成",
"statusFailed": "失败",
"busy": "任务执行中,稍后再删",
"deleted": "已删除",
"failed": "操作失败",
"loadFailed": "加载任务失败",
"loadAppsFailed": "加载应用失败",
"makeVersion": "生成版本",
"makeVersionHint": "把加壳产物写成一条新的版本记录:客户端按版本记录 ID 递增判定更新,原地换包推不下去。其余资源文件沿用来源版本。",
"versionLabel": "版本号",
"versionPlaceholder": "留空则按来源版本末段 +1",
"strategy": "更新策略",
"strategyOptional": "可选更新(optional)",
"strategyForced": "强制更新(forced)",
"changelog": "更新说明",
"changelogPlaceholder": "例如:接入验证壳,需登录后使用",
"publishNow": "创建后立即发布(否则存为草稿)",
"cancel": "取消",
"confirm": "确定",
"working": "处理中…",
"published": "已生成版本 {v}"
}
},
"auth": {
@@ -2840,7 +2883,11 @@
"noUsers": "暂无用户记录",
"username": "用户名",
"email": "邮箱",
"status": "状态",
"status": {
"active": "正常",
"disabled": "禁用",
"banned": "封禁"
},
"registerTime": "注册时间",
"lastLogin": "最后登录",
"active": "正常",
@@ -2876,11 +2923,6 @@
"expired": "已过期",
"daysLeft": "天剩余"
},
"status": {
"active": "正常",
"disabled": "禁用",
"banned": "封禁"
},
"create": {
"title": "创建用户",
"description": "在您的应用下创建新用户",
@@ -2981,7 +3023,6 @@
"exportBtn": "导出",
"batchExportBtn": "批量导出",
"application": "应用",
"cardType": "卡类",
"reset": "重置",
"select": "选择",
"columns": {
@@ -3014,7 +3055,7 @@
"selectAppPlaceholder": "请选择应用",
"selectCardTypeLabel": "选择卡类",
"selectCardTypePlaceholder": "请选择卡类",
"quantity": "生成数量",
"quantity": "数量",
"quantityPlaceholder": "请输入生成数量",
"quantityHint": "单次最多生成 100 张卡密",
"estimatedCost": "预计费用",
@@ -3029,7 +3070,6 @@
"application": "选择应用",
"selectApplication": "请选择应用",
"cardType": "选择卡类",
"selectCardType": "请选择卡类",
"noCardType": "该应用暂无可用卡类",
"count": "生成数量",
"maxCount": "单次最多生成 100 张卡密",
@@ -3037,7 +3077,6 @@
"app": "应用",
"type": "卡类",
"unitPrice": "单价",
"quantity": "数量",
"units": "张",
"totalAmount": "预计费用",
"generateNow": "立即生成"
@@ -3253,7 +3292,8 @@
"normal": "正常",
"storage": "存储",
"admin": "管理员",
"agent": "代理商"
"agent": "代理商",
"protect": "加壳加固"
},
"footer": {
"brand": "网络验证",
+6
View File
@@ -107,6 +107,12 @@ const routes: RouteRecordRaw[] = [
component: () => import('@/pages/admin/versions/index.vue'),
meta: { title: '版本管理 - 管理后台' },
},
{
path: 'protect',
name: 'AdminProtect',
component: () => import('@/pages/admin/protect/index.vue'),
meta: { title: '加壳加固 - 管理后台' },
},
{
path: 'versions/create',
name: 'AdminVersionCreate',
+13 -3
View File
@@ -14,9 +14,6 @@ import type {
ParamValueZeroOrMore,
ParamValueZeroOrOne,
} from 'vue-router'
import type {
_ExtractParamParserType,
} from 'vue-router/experimental'
declare module 'vue-router' {
interface TypesConfig {
@@ -342,6 +339,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/admin/protect/': RouteRecordInfo<
'/admin/protect/',
'/admin/protect',
Record<never, never>,
Record<never, never>,
| never
>,
'/admin/risk-control/': RouteRecordInfo<
'/admin/risk-control/',
'/admin/risk-control',
@@ -948,6 +952,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/admin/protect/index.vue': {
routes:
| '/admin/protect/'
views:
| never
}
'src/pages/admin/risk-control/index.vue': {
routes:
| '/admin/risk-control/'